This week's book giveaway is in the OCAJP forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff 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 OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "TreeSet Null" Watch "TreeSet Null" New topic
Author

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
Bartender

Joined: Feb 26, 2001
Posts: 5347
    
  13

It has to do with natural ordering and the use of compareTo() -- see http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html


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

Joined: Apr 06, 2010
Posts: 4502
    
    8

If you look at java.util.TreeSet#add(E), you'll see that it says:
Throws:
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
Bartender

Joined: Feb 26, 2001
Posts: 5347
    
  13

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.
 
wood burning stoves
 
subject: TreeSet Null