From the Java 6 TreeSet<E>
Documentation:
boolean remove(Object o):
Removes the specified element from this set if it is present.
Why does this accept an Object instead of the generic type E? The only objects that can be added are of type E, so it follows that the only removable type should be of type E.
TreeSet remove() Method in JavaTreeSet. remove(Object O) method is to remove a particular element from a Tree set. Parameters: The parameter O is of the type of Tree set and specifies the element to be removed from the set.
The equals() method of java. util. TreeSet class is used to compare the specified object with this set for equality. Returns true if and only if the specified object is also a set, both sets have the same size, and all corresponding pairs of elements in the two sets are equal.
This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare ) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.
Objects in a TreeSet are stored in a sorted and ascending order. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
Taking the answer from the first comment posted:
Myth:
A popular myth is that it is stupid and evil, but it was necessary because of backward compatibility. But the compatibility argument is irrelevant; the API is correct whether you consider compatibility or not.
Real reason:
Uniformly, methods of the Java Collections Framework (and the Google Collections Library too) never restrict the types of their parameters except when it's necessary to prevent the collection from getting broken.
Read more here: Why does Set.contains() take an Object, not an E?
remove()
, like get()
is required to work when given an equal element (in terms of .equals()
). In Java, it is possible (and in some cases, required) for objects of different classes to be equal. Hence, you shouldn't restrict the type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With