ジェネリックスを正しく理解している場合、として宣言されたパラメーターを持つメソッドは、Typeまたはスーパータイプの<? super T>
いずれかの参照を受け入れます。次のコードでこれをテストしようとしていますが、コンパイラーはそれを好みません。T
T
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
class ZiggyTest2{
public static void main(String[] args){
List<Animal> anim2 = new ArrayList<Animal>();
anim2.add(new Animal());
anim2.add(new Dog());
anim2.add(new Cat());
testMethod(anim2);
}
public static void testMethod(ArrayList<? super Dog> anim){
System.out.println("In TestMethod");
anim.add(new Dog());
//anim.add(new Animal());
}
}
コンパイラエラーは:
ZiggyTest2.java:16: testMethod(java.util.ArrayList<? super Dog>) in ZiggyTest2 cannot be applied to (java.util.List<Animal>)
testMethod(anim2);
^
1 error
<Animal>
anim2はタイプであり、Animalはスーパータイプの犬であるため、なぜ私がanim2を渡せないのかわかりません。
ありがとう