This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

TreeSet Null  RSS feed

 
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
Sheriff
Posts: 11144
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac 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: 4568
9
  • 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
Sheriff
Posts: 11144
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac 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
Boost this thread!