Java generic collection, cannot add list to list

后端 未结 1 1061
鱼传尺愫
鱼传尺愫 2020-12-20 17:41

Why does the following

public class ListBox {
    private Random random = new Random();
    private List> box;

pub         


        
相关标签:
1条回答
  • 2020-12-20 18:36

    You've declared box to be a List of something that extends Collection of Object. But according to the Java compiler, it could be anything that extends Collection, i.e. List<Vector<Object>>. So it must disallow add operations that take the generic type parameter for this reason. It can't let you add an ArrayList<Object> to a List that could be List<Vector<Object>>.

    Try removing the wildcard:

    private List<Collection<Object>> box;
    

    This should work because you can certainly add an ArrayList<Object> to a List of Collection<Object>.

    0 讨论(0)
提交回复
热议问题