在以下代码示例中:
interface Eatable{ public void printMe();}
class Animal { public void printMe(){System.out.println("Animal object");}}
class Dog extends Animal implements Eatable{ public void printMe(){System.out.println("Dog object");}}
class BullTerrier extends Dog{ public void printMe(){System.out.println("BullTerrier object");}}
public class ZiggyTest{
public static void main(String[] args) throws Exception{
Object[] objArray = new Object[]{new Object(), new Object()};
Collection<Object> objCollection = new ArrayList<Object>();
Animal[] animalArray = new Animal[]{new Animal(),new Animal(),new Animal()};
Collection<Animal> animalCollection = new ArrayList<Animal>();
Dog[] dogArray = new Dog[]{new Dog(),new Dog(),new Dog()};
Collection<Dog> dogCollection = new ArrayList<Dog>();
System.out.println(forArrayToCollection(animalArray,animalCollection).size());
// System.out.println(forArrayToCollection(dogArray,dogCollection).size()); #1 Not valid
System.out.println(genericFromArrayToCollection(animalArray,animalCollection).size());
System.out.println(genericFromArrayToCollection(dogArray,dogCollection).size());
System.out.println(genericFromArrayToCollection(animalArray,objCollection).size()); //#2
System.out.println(genericFromArrayToCollection(dogArray,animalCollection).size()); //#3
// System.out.println(genericFromArrayToCollection(objArray,animalCollection).size()); //#4
}
public static Collection<Animal> forArrayToCollection(Animal[] a, Collection<Animal> c){
for (Animal o : a){
c.add(o);
}
return c;
}
static <T> Collection<T> genericFromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o);
}
return c;
}
}
为什么编译器genericFromArrayToCollection()
只有在集合的声明类型是数组声明类型的父级时才允许调用该方法(参见标记为 #2、#3 和 #4 的行)。请问这是为什么?
谢谢
编辑
当我取消注释标记为 #4 的行时,出现以下错误
ZiggyTest.java:34: <T>genericFromArrayToCollection(T[],java.util.Collection<T>) in ZiggyTest cannot be applied to (java.lang.Object[],java.util.Collection<Animal>)
System.out.println(genericFromArrayToCollection(objArray,animalCollection).size()); //#4
^
1 error
编辑 2
@Tudor 我使用此语句尝试了以下方法
System.out.println(method1(new ArrayList<String>()).size());
编译器报错说不能应用于 java.util.ArrayList
public static Collection<Object> method1(ArrayList<Object> c){
c.add(new Object());
c.add(new Object());
return c;
}