Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between null and empty list?

Tags:

java

List<Map<String, Object>> pcList = null;
Map<String, Object> pcMap = new HashMap<String, Object>();
ComputerConfigurations tempPC = null;

if (historyList != null) {
    Iterator<ComputerConfigurations> iterator = historyList.iterator();
    while (iterator.hasNext()) {
        tempPC = (ComputerConfigurations) iterator.next();
        pcMap.put(tempPC.getEnvironment(), tempPC);
        pcList.add((Map<String, Object>) pcMap);
    }
}

I am getting null pointer exception on pcList.add((Map<String, Object>)pcMap); line. [Servlet Error]-: java.lang.NullPointerException . Any suggestion ?

like image 633
Peter P Avatar asked Dec 16 '15 06:12

Peter P


People also ask

What is the difference between null and empty array?

null array—-when the size of array is not declared than the array is known as null array. EMPTY ARRAY——-if an array having the size but not values than it's known as empty array.

What is difference between null and empty in SQL?

NULL is used in SQL to indicate that a value doesn't exist in the database. It's not to be confused with an empty string or a zero value. While NULL indicates the absence of a value, the empty string and zero both represent actual values.

Is an empty ArrayList the same as null?

No. An ArrayList can be empty (or with nulls as items) an not be null. It would be considered empty.

What is empty list?

The emptyList() method of Java Collections class is used to get a List that has no elements. These empty list are immutable in nature.


1 Answers

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<Map<String, Object>> 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).

like image 109
ajb Avatar answered Oct 26 '22 16:10

ajb