Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the java collections accepts adding null values?

I know Set and Map accepts null values and today I just found out LinkedList also accepts null values like

   map.put(null, 1);
   set.add(null);
   linkedList.add(null)

Is there any other collections that allow null values to be stored?. Just posting to get a comprehensive list in one place and reason for each for them.

like image 217
Ijaz Avatar asked Jan 25 '23 22:01

Ijaz


1 Answers

Set and Map are interfaces. They have several implementations in Java.

Popular implementations of the Map are:

  1. HashMap - accepts one null key
  2. Hashtable - doesn't accept any null key
  3. TreeMap - doesn't accept any null key
  4. LinkedHashMap - accepts one null key

Any number of null values can be added as value in any of above implementations


Popular implementations of the Set are:

  1. HashSet - accepts one null element
  2. TreeSet - doesn't accept any null element
  3. LinkedHashSet - accepts one null element

Any implementations of List, like ArrayList or LinkedList can accept nulls.

like image 122
Giorgi Tsiklauri Avatar answered Feb 07 '23 12:02

Giorgi Tsiklauri