简体   繁体   English

Java泛型和集合的问题

[英]Problems with Java generics and collections

I have a class that represents a tree-like structure, the essential bits look like this: 我有一个表示树状结构的类,基本位如下所示:

public Node<T> placeAll(Collection<T> elements){    
    for (T e : elements)
        addElement(e);

    // LOG/DEBUG etc
    return root;
}

public void addElement(T el) {
    Node<T> node = new Node<T>(el);
    addElement(root, node);
}

private void addElement(Node<T> parent, Node<T> child) {
    // .... PLACE THE NODE
}

Now this works perfectly fine when I place the nodes one by one in a test case: 现在,当我将节点逐个放在测试用例中时,这种方法非常好用:

public void test() {

    List<Integer> s1 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
    // 13 more lists
    List<Integer> s15 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 221, 251); 

    Hypergraph<Object> hg = new Hypergraph<>(...);

        hg.addElement(s1);
        System.out.println(hg.getRoot().toStringTree());
        System.out.println();
              .
              .
              .
        hg.addElement(s15);
        System.out.println(hg.getRoot().toStringTree());
        System.out.println();
    }

If I add the following line hg.placeAll(Arrays.asList(s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15)); 如果我添加以下行hg.placeAll(Arrays.asList(s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15));

to my test case, I get an error regarding the use of generics: 对于我的测试用例,我收到有关泛型使用的错误:

The method placeAll(Collection<Object>) in the type Hypergraph<Object> is not applicable for the arguments (List<List<Integer>>)

I don't quite understand this... If addElement(T el) works fine when I call it with T resolved to List<Integer> , why does List<List<Integer>> comply to placeAll(Collection<T> c) ? 我不太明白这一点...如果我用T解析为List<Integer>调用addElement(T el)工作正常,为什么List<List<Integer>>符合placeAll(Collection<T> c) Considering that List<T> is a Collection<T> I can't make sense out of this.. 考虑到List<T>Collection<T>我无法理解这一点..

The problem is that the method expects a Collection<Object> (as T seems to be Object in your example), but you are passing a Collection<List<Integer>> . 问题是该方法需要Collection<Object> (在您的示例中T似乎是Object ),但是您传递的是Collection<List<Integer>> And while a List<Integer> is an Object , a Collection<List<Integer>> is not a subclass of a Collection<Object> . 虽然List<Integer>是一个Object ,但Collection<List<Integer>> 不是 Collection<Object>的子类。

Change the method signature to accept a Collection<? extends T> 更改方法签名以接受Collection<? extends T> Collection<? extends T> , then it should work. Collection<? extends T> ,然后它应该工作。

public Node<T> placeAll(Collection<? extends T> elements) {   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM