Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

TreeSet Null

 
Shahir Deo
Ranch Hand
Posts: 80
Hibernate Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Guys,

Why TreeSet does not allow NULL Values to be stored? and Throws java.lang.NullPointerException
 
Junilu Lacar
Bartender
Pie
Posts: 7264
44
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 7264
44
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic