This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 78

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: 4442

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: 4341

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: 4442

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.
It is sorta covered in the JavaRanch Style Guide.
subject: TreeSet Null
Similar Threads
TreeSet adding twice null
Why Null Pointer Exception?
TreeSet & TreeMap confusion
NullPointerException in TreeSet
TreeSet problem