0
0

More than 1 year has passed since last update.

型推論

Last updated at Posted at 2023-02-09

代入、値の受け取りで、宣言部のtypeと値を渡す側のtypeがチェックされる
以下の例ではnew arrayList()のが、declare のListのと型があっているかチェックされる
<>(型未指定)、もしくは以外はエラーになる

public class Outer {
    public static void main(String args[]) {
        method(new ArrayList<>());
        method(new ArrayList<String>());   //warn  2重定義
        method(new ArrayList<Object>());   //err
        method2(new ArrayList<>());
        method2(new ArrayList<String>());  //err
        method2(new ArrayList<Object>());  //warn
    }
    static void method(List<String> l) {
        l.forEach(System.out::println);
    }
    static void method2(List<Object> l) {
        l.forEach(System.out::println);
    }
}
-------------------------------------------------------------
COMPILATION ERROR : 
-------------------------------------------------------------
com/mycompany/mavenproject1/Outer.java:[16,16] 不適合な型: java.util.ArrayList<java.lang.Object>をjava.util.List<java.lang.String>に変換できません:
com/mycompany/mavenproject1/Outer.java:[18,17] 不適合な型: java.util.ArrayList<java.lang.String>をjava.util.List<java.lang.Object>に変換できません:
2 errors 
-------------
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0