File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes TreeSet Null Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "TreeSet Null" Watch "TreeSet Null" New topic

TreeSet Null

Shahir Deo
Ranch Hand

Joined: Mar 19, 2013
Posts: 80

Hello Guys,

Why TreeSet does not allow NULL Values to be stored? and Throws java.lang.NullPointerException

Knowledge enlivens the soul.
Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

It has to do with natural ordering and the use of compareTo() -- see

Junilu - [How to Ask Questions] [How to Answer Questions]
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

If you look at java.util.TreeSet#add(E), you'll see that it says:
NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

So if you want a TreeSet that can contain null, write your own Comparator, and use that to create the TreeSet.
Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

If you write your own Comparator, remember that elements in a TreeSet are ordered so you must write the Comparator such that its compareTo() method treats null sensibly and that it is consistent with equals(), which always returns false when passed null.
I agree. Here's the link:
subject: TreeSet Null
It's not a secret anymore!