aspose file tools*
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
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: 5288
    
  10

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: 4490
    
    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: 5288
    
  10

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: http://aspose.com/file-tools
 
subject: TreeSet Null