3

Why TreeSet does not allow null value in Java?

 2 years ago
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.
neoserver,ios ssh client

Why TreeSet does not allow null value in Java?

           TreeSet implements Set interface and maintains unique elements which means it doesn't allow duplicates. The elements in the TreeSet are sorted and in ascending order. In this post, we will discuss about why TreeSet doesn't allow to add null value ?

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;
Java 1.6 and earlier versions, TreeSet allow to add first element as null. From 1.7 onwards null is not accepted at all.


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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK