Java generics and array initialization

后端 未结 4 1291
谎友^
谎友^ 2020-12-01 12:41

What\'s the explanation for the following:

public class GenericsTest {
    //statement 1
    public ArrayList[] lists;

    public GenericsTes         


        
4条回答
  •  日久生厌
    2020-12-01 13:23

    In this case, I would avoid using arrays for just this reason. The declaration of "lists" in your original code could be

    List> lists = new ArrayList>(4);
    for(int i = 0; i < 4; i++) lists.add(null); // or add an empty ArrayList
    

    (you should use the interface rather than the implementation in variable declarations)

    Instead of array [] syntax, you would use get() or set(). Other than that, it's equivalent.

提交回复
热议问题