| Author |
NullPointerException in TreeSet
|
Naresh Chaurasia
Ranch Hand
Joined: May 18, 2005
Posts: 309
|
|
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: 431
|
|
|
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: 431
|
|
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.
|
 |
 |
|
|
subject: NullPointerException in TreeSet
|
|
|