Search code examples
javaarraylistgeneric-collections

Java Arraylist remove method takes Object as parameter, not E


For a typed ArrayList list<E> , why isn't remove method is like

public boolean remove(E e) {
}

remove() and contains() method takes Object o as parameter. while add() takes E. There is a likelihood someone can call remove() with different object type and get Runtime Error.


Solution

  • Arraylist actually stores the items in an Object array:

    Object[] elementData;

    In the remove() method, it does a comparison with the items in the array using the equals method comparing 2 objects, and if nothing is found it doesn't do anything. (and does not throw a Runtime Error as you believe) It doesn't need to care about if the types match what is in the array.

    Also, paraphrasing the answer here, if we had an ArrayList<Cat> cats, and Cat extends Animal, then we should be able to call the remove on cats the following way:

    Animal siameseCat = new Cat("purrykitty"); cats.remove(siameseCat);

    If remove enforced that it take only an object of type Cat, then this removal would've thrown an error despite being a reasonable request.

    The add() method on the other hand needs to ensure that the array does not contain mismatched items.