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