Why is, in Collection<T>, the method boolean remove(Object o) not defined as boolean remove(T o)?
When I have a Collection<String> list i’m sure that I don’t want to do list.remove(new Date()) for instance.
Edit: already solved: Why aren't Java Collections remove methods generic?
Question 2:
When I have a class:
class Value {
Object getValue() {
// return something;
}
}
and then I want to implement a new cool list:
class CoolList<T extends Value> implements Collection<T> {
// ...
@Override
public boolean remove(Object o) {
try {
T value = (T) o; // I mean the cast here
removeInternal(value);
} catch (ClassCastException e) {
return false;
}
}
}
How can I do a clean cast without producing a warning (unchecked cast) and without using @SuspressWarning, is this even possible?
Edit:
Internally I want the list to be able to recover deleted items and because of that I have internally a List<T> deletedItems.
So the removeInternal() method appends the item to be deleted to the internal deletedItems list and then deletes it and because of that I need some sort of cast.
Thank you.
Regarding your second question: just make
removeInternalnon-generic. It should use the same logic that is described in the answer to your first question:removeInternal(o)removes an objectesuch that(o==null ? e==null : o.equals(e))is true. (If you implement logic that is not equivalent to this, you are violating the contract for theCollectioninterface.) There’s no need for a genericremoveInternal.EDIT Here’s an example of how one might implement a non-generic
removeInternal:This assumes that
removeElementAt(int)will correctly transfer theith item todeletedItemsand adjust the internal count of items. It’s important to note that the element that was removed is not necessarily the same object as is passed in the argument; it just the first element that satisfies the equality predicate.