Thursday, 15 December 2016

Why TreeSet does not accept null value ?

In TreeSet, all elements are sorted according to the natural ordering of the element. Also it does not contain duplicate and null value. If you want to modify the natural ordering of the element, you can use your own Comparator at the time initialization, to sort its value based on your own logic.

If you try to store null value , it throws NullPointerExeption .

The reason is, if you look at the internal implementation of the TreeSet, it uses natural ordering, that means TreeSet uses Comparable interface by default to sort its value by comparing other value. 

Just think programmatically, how will you compare the null value to other. Is it make sense to compare the value with other(NULL) which doesn't have any value in it.  That's why java developer made it TreeSet such a way that, it will throw NullPointerExeption when you try to store null value.


And also if you look at the definition of add method in TreeSet

add Method in TreeSet

  public boolean add(E e) throws NullPointerExeption {  
     return m.put(e, PRESENT)==null;  
  }  

Hope you clear with the explaination.




If you like the above solution . Please share this blog

No comments:

Post a Comment

s