Why TreeSet does not allow null value in Java?
source link: http://adnjavainterview.blogspot.com/2019/10/why-treeset-does-not-allow-null-values.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Why TreeSet does not allow null value in Java?
Example to add null value to TreeSet:--
TreeSetExample.java
package com.example.demo; import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { TreeSet<String> treeSet = new TreeSet<String>(); treeSet.add(null);
}
}
Output:-
Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at com.example.demo.TreeSetExample.main(TreeSetExample.java:10)
Why TreeSet doesn't allow to add null value ?
TreeSet internally used Comparable interface to sort the elements in ascending order. In Comparable interface there is method called compareTo() used to compare one value with other to sort the elements. So null doesn't have any value because of this reason compareTo() method can not compare null with other value, giving NullPointerException.
add method declaration :-
public boolean add(E e) throws ClassCastException, NullPointerExeption;
Related Posts:--
1) Collection Hierarchy in Java
2) Collection Interview Questions and Answers in Java(List,Map & Set)
3) How to iterate the TreeMap in reverse order in Java
4) How to Remove duplicates from ArrayList in Java
5) Internal Implementation of TreeMap in Java
6) Internal implementation of ArrayList in Java
7) Internal Implementation of LinkedList in Java
8) Difference between HashSet and TreeSet in Java
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK