Java generics and array initialization

后端 未结 4 1288
谎友^
谎友^ 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:25

    It's because you can't create, but you can use them:

    public class GenericsTest {
        //statement 1
        public ArrayList[] lists;
    
        public GenericsTest()
        {
            //statement 2
            lists = new ArrayList[4];
            //statement 3
            lists[0].add(new Integer(0));
            //statement 4
            lists[0].add(new String(""));
        }
    }
    

    Statement 3 is possible, statement 4 will lead to a compiler error.

提交回复
热议问题