File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointerException in TreeSet

 
Naresh Chaurasia
Ranch Hand
Posts: 361
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code


gives null pointer exception. I know that when the element is being added to TreeSet, which has to be maintained in sorted order, each element being added is compared with existing elements in TreeSet. If there is already null or null is added to TreeSet having elements, it will throw null pointer exception.

If such a case happens while using TreeSet then we can never TreeSet collection with null and other elements. If it is so then what is the purpose of allowing null in TreeSet.
 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From javadocs:


ClassCastException - if the specified object cannot be compared with the elements currently in this set
NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

for add method

In the above code ,shouldn't add method throw ClassCastException instead of NullPointerException ???
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I recently posted in another topic about this question here. It's because of TreeMap (internally used by the TreeSet) doesn't check for a null value if it's the first element. Otherwise it does. It throws a NullPointerException because the String comparable uses a method on the null reference.
 
Arjun Srivastava
Ranch Hand
Posts: 432
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
elements in treeset must be comparable(i.e. they must implement the interface comparable).
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes but that's not the problem here. The only element used is String and that class implements the Comparable interface.
 
Arjun Srivastava
Ranch Hand
Posts: 432
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi wouter
yeah didn't saw above code clearly,your reason is right.
but saw your previous code where you have written code that any human can understand.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic