Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList indexOf generic type [duplicate]

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?

like image 862
Vladimir Kishlaly Avatar asked Mar 12 '26 09:03

Vladimir Kishlaly


1 Answers

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.

like image 95
Ian Roberts Avatar answered Mar 13 '26 23:03

Ian Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!