Question

ArrayList described as

public class ArrayList<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

And most of main methods work with E generic type (get, set, add, addAll etc).

But methods contains, indexOf, lastIndexOf and remove take the Object type as parameter - is this only because of inner use or Object.equals() or anything else?

Was it helpful?

Solution

The collection types only use their generic type E in cases where it must match in order for the operation to be legal. If you have a list of strings then clearly something like add can only make sense when passed a string.

But for operations like contains it's different - it is perfectly legal to ask whether a list of strings contains a particular Integer, for example. The answer will always be no, but that doesn't make it an error to ask the question.

OTHER TIPS

From the Java 7 API for ArrayList#contains()

public boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

Looking at this, it's saying that the comparison to determine whether o is a member of the list depends upon o's implementation of the equals() method. By specify the parameter type as Object, we can put the responsibility for determining equality on the input object's class, rather than E, the type parameter of the list.

That is because contains, lastIndexOf, remove etc. methods need to check for the equality of objects before performing corresponding actions, which done by using equals method. And equal method comes from object class which should be overridden by generic type E object. On the contarary to this get, set, add etc methods do not need any comparision.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top