Core Java

Java Collections Null Values Tolerance Limitations

In Java, the Collections Framework provides various data structures to store and manipulate data. However, not all collections handle null values the same way. Some collections allow null values, while others impose restrictions. Understanding these behaviours is essential to avoid runtime exceptions and design robust applications.

This article explores how common collection types like List, Set, Map, and their implementations (ArrayList, HashSet, TreeSet, etc.) handle null values, including their tolerance and restrictions.

1. Lists and null Values

The List interface and its common implementations like ArrayList and LinkedList allow null values. However, CopyOnWriteArrayList imposes some constraints on concurrent modifications. Here is an example of adding null Values to an ArrayList:

01
02
03
04
05
06
07
08
09
10
11
public class NullInArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        list.add(null);
        list.add("Collections");
        list.add(null);
 
        System.out.println("ArrayList with null values: " + list);
    }
}

In this example, we demonstrate how ArrayList handles null values. The add() method of ArrayList permits adding null, and we insert multiple null values into the list.

Output:

1
ArrayList with null values: [Java, null, Collections, null]

The output shows that ArrayList can store multiple null values. This is because ArrayList does not impose any restrictions on null elements. However, care must be taken to handle null values during operations like sorting, as it may throw NullPointerException.

2. Sets and null Values

The Set interface allows at most one null value because sets do not permit duplicate elements. However, specific implementations behave differently:

  • HashSet: Allows a single null value.
  • TreeSet: Throws a NullPointerException because it uses a comparator to sort elements.
  • LinkedHashSet: Similar to HashSet, it allows a single null.

Here is an example demonstrating the use of null in HashSet and TreeSet.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
public class NullInSetExample {
    public static void main(String[] args) {
        HashSet<String> hashSet = new HashSet<>();
        hashSet.add("Java");
        hashSet.add(null);
        hashSet.add("Collections");
        hashSet.add(null);
 
        System.out.println("HashSet with null values: " + hashSet);
 
        try {
            TreeSet<String> treeSet = new TreeSet<>();
            treeSet.add("Java");
            treeSet.add(null); // Throws NullPointerException
        } catch (NullPointerException e) {
            System.out.println("TreeSet does not allow null values. ");
        }
    }
}

In this example, we demonstrate the behaviour of HashSet and TreeSet when handling null values. HashSet allows a single null value, while TreeSet does not allow null at all.

Output:

1
2
HashSet with null values: [null, Java, Collections]
TreeSet does not allow null values.

The output shows that the HashSet retains only one null value because it eliminates duplicates. In contrast, the TreeSet throws a NullPointerException when attempting to add a null value since it requires elements to be comparable for sorting.

3. Maps and null Keys/Values

The Map interface allows null keys and values, but the behaviour varies by implementation:

  • HashMap: Allows one null key and multiple null values.
  • TreeMap: Throws a NullPointerException for null keys but allows null values.

Below is an example demonstrating null handling in HashMap and TreeMap.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
public class NullInMapExample {
    public static void main(String[] args) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(null, "Java");
        hashMap.put("Key1", null);
        hashMap.put("Key2", null);
 
        System.out.println("HashMap with null key and values: " + hashMap);
 
        try {
            TreeMap<String, String> treeMap = new TreeMap<>();
            treeMap.put(null, "Java"); // Throws NullPointerException
            System.out.println(" " + treeMap);
        } catch (NullPointerException e) {
            System.out.println("TreeMap does not allow null keys.");
        }
    }
}

The above example showcases the behaviour of HashMap and TreeMap regarding null keys and values. HashMap supports a single null key and multiple null values, while TreeMap rejects null keys but allows null values.

Output

1
2
HashMap with null key and values: {null=Java, Key2=null, Key1=null}
TreeMap does not allow null keys.

The HashMap works as expected, allowing a single null key and multiple null values. However, the TreeMap throws an exception because its natural ordering or custom comparator cannot handle null keys.

4. Best Practices with null in Collections

  • Avoid null where possible: Use Optional for optional values or empty collections instead of null.
  • Choose appropriate implementations: Select the collection type based on your requirements for handling null.
  • Handle null explicitly: Always check for null before performing operations like sorting or key lookups.

5. Conclusion

In this article, we explored how Java Collections handle null values, highlighting the tolerance and limitations across different collection types such as List, Set, and Map. Through examples, we demonstrated how implementations like ArrayList, HashSet, and HashMap allow null values, while others like TreeSet and TreeMap impose restrictions. Understanding these behaviours is essential for designing reliable applications and avoiding runtime errors.

6. Download the Source Code

This article was on the tolerance and limitations of null values in Java Collections.

Download
You can download the full source code of this example here: Java collections null values tolerance limitations
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button