Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java's TreeSet<E> remove(Object) not take an E

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.

like image 602
ComputerDruid Avatar asked Nov 04 '11 21:11

ComputerDruid


People also ask

How do I remove an object from TreeSet?

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.

Does TreeSet use equal?

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.

Does TreeSet use compareTo?

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.

Is TreeSet an ordered collection?

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.


2 Answers

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?

like image 84
zengr Avatar answered Nov 14 '22 11:11

zengr


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.

like image 33
newacct Avatar answered Nov 14 '22 12:11

newacct