"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
SCJP6.0,My blog Ranchers from Delhi
Wouter Oet wrote:Internally the TreeSet uses a TreeMap. And the TreeSet.add() delegates it to TreeMap.put(). Just open the source of that method and you'll see the bug. There is even a comment about the bug.
Huachaitou Peek wrote:
Wouter Oet wrote:Internally the TreeSet uses a TreeMap. And the TreeSet.add() delegates it to TreeMap.put(). Just open the source of that method and you'll see the bug. There is even a comment about the bug.
How can I take a look at source code ? Is there an easy way to do that ? Thanks.
Huachaitou Peek wrote:How can I take a look at source code ? Is there an easy way to do that ? Thanks.
Although that sounds like a plausible answer and matches with the external behavior, it's not what happens internally.Harpreet Singh janda wrote:This exception is due to the fact that the TreeSet maintains the order of the elements added. Whenever we add an element to the TreeSet it compare the added element with already existing elements to find the correct position of the newly added element.
So if the TreeSet will be empty the first element will be directly added to the TreeSet as there are no elements to be compared.
But if there is any element in the TreeSet, it will through a null pointer exception when newly added element will be compared with the already existing elements (as any operation on a null object throw null pointer exception).
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Actually it does. This runs without exceptions:Harpreet Singh janda wrote:It does not matter whether we are using a custom comparator or the one provide by the java itself.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Harpreet Singh janda wrote:That means NPE is due to the comparator not the internal structure of TreeSet.
Wouter Oet wrote:So:
add(null); add(null); throws NullPointerException because of the null check
add(null); add("JavaRanch"); throws NullPointerException because the String comparable uses a method of the null value
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Don't get me started about those stupid light bulbs. |