wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes NullPointerException in TreeSet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "NullPointerException in TreeSet" Watch "NullPointerException in TreeSet" New topic

NullPointerException in TreeSet

Naresh Chaurasia
Ranch Hand

Joined: May 18, 2005
Posts: 356
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.

SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

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 ???

OCPJP 6.0 93%
OCPJWCD 5.0 98%
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

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.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Arjun Srivastava
Ranch Hand

Joined: Jun 23, 2010
Posts: 432

elements in treeset must be comparable(i.e. they must implement the interface comparable).

SCJP 6 | FB : Java Certifications-Help. | India Against Corruption
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

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

Joined: Jun 23, 2010
Posts: 432

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.
jQuery in Action, 2nd edition
subject: NullPointerException in TreeSet
Similar Threads
TreeSet uses compareTo
TreeSet adding twice null
question about treeSet (K&B) Chapter 7 Question 3
TreeSet Problem
TreeSet problem