2

有任何方法可以解决这种情况(我试图尽可能简化这种情况):

public class Test {

    public static void main(String[] args) {

        /*
         * HERE I would like to indicate that the CollectionGeneric can be of
         * something that extends Animal (but the constructor doesn't allow
         * wildcards)
         */
        CollectionGeneric<? extends Animal> animalsCollectionGeneric = new CollectionGeneric<Animal>();
        List<? extends Animal> animals = getAnimals();
        /* Why I cannt do that? */
        animalsCollectionGeneric.setBeans(animals);
    }

    private static List<? extends Animal> getAnimals() {
        return new ArrayList<Dog>();
    }
}

class CollectionGeneric<T> {
    private List<T> beans;

    public List<T> getBeans() {
        return (beans != null) ? beans : new ArrayList<T>();
    }

    public void setBeans(List<T> beans) {
        this.beans = beans;
    }
}

interface Animal {}

class Dog implements Animal{}

这种情况给了我下一个错误:

The method setBeans(List<capture#2-of ? extends Animal>) in the type    
CollectionGeneric<capture#2-of ? extends Animal> is not applicable for
the arguments (List<capture#3-of ? extends Animal>)*

我不确定是否有办法用泛型做到这一点,

4

1 回答 1

7

这意味着不能证明这两个集合具有相同的类型边界:

    CollectionGeneric<? extends Animal> animalsCollectionGeneric = 
             new CollectionGeneric<Animal>(); 
    List<? extends Animal> animals = getAnimals()

第一个可能在运行时有CollectionGeneric<Tiger>,第二个可能在运行时有List<Gnu>。混合这些将意味着您失去类型安全性(更不用说大屠杀了)。

因此,您需要向编译器证明这两者是相关的,因此您的通用签名应该是:

public void setBeans(List<? extends T> beans) {}
public List<T> getBeans();

并用作:

List<? extends Animal> beans = getBeans();
GenericCollection<Animal> animals = new GenericCollection<Animal>();
animals.add(beans);
于 2009-07-10T11:15:14.553 回答