What is difference between null and empty list?

后端 未结 4 2022
别跟我提以往
别跟我提以往 2021-01-19 01:14
List> pcList = null;
Map pcMap = new HashMap();
ComputerConfigurations tempPC = null;

if         


        
4条回答
  •  Happy的楠姐
    2021-01-19 01:59

    In Java, collections won't magically spring into existence just by adding something to them. You have to initialize pcList by creating an empty collection first:

    List> pcList = new ArrayList<>();
    

    An empty collection isn't the same as null. An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.

    Note that an object can't be of type List, because that's an interface; therefore, you have to tell Java what kind of List you really want (such as an ArrayList, as I've shown above, or a LinkedList, or some other class that implements List).

提交回复
热议问题