views:

94

answers:

3

Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic

This is similar to the question here, on java.util.Map. This question is left as a pointer to that question.


The List interface contains several methods which still accept an Object as parameter, after generics were introduced in Java 5. Such as:

boolean contains(Object o)
int lastIndexOf(Object o)
boolean remove(Object o)

I was expecting these methods to make use of the type parameter. Something like this:

boolean contains(E e) // Where the interface is defined as List<E>

Although, it would have to be <? extends E>, but I'm not sure of the syntax for that.

Is there a design reason why these methods take an Object, or is it for backwards bytecode compatibility, or is it another reason?

+1  A: 

I believe it is so you can still allow different types of objects in the collection that aren't necessarily all subclasses of a given type E.

Poindexter
+1  A: 

The type parameters are only really used to ensure that anything that is added to or retrieved from the list is of the correct type. It doesn't care if you give it an object of another type to look for in the collection, since it will only be using Object.equals() when doing that anyway. It simply will not find it, which is the expected behavior.

Edit: Kevin B's blog post about it, referenced in the comments, is a much better explanation.

ColinD
"It simply will not find it" No, it's possible for objects of different types to be equal. That's the real reason why you are able to give any type of object.
newacct
A: 

The intent of the generics is to make sure you always know what type you're handling. Those methods aren't "dangerous", they can't harm the type-ness of the collection, and so there was no need to add generics to them when the move was made in Java 5.

abyx