2

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.

MIK
  • 392
  • 3
  • 19
  • No. There is **absolutely no chance** that calling `remove` with any type will cause a `ClassCastException`. All `remove` does is loop through the `List` and test `equals` against each element. There are no operations that will involve casting - if `equals` is implemented correctly. – Boris the Spider Oct 01 '15 at 20:41

1 Answers1

1

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.

Community
  • 1
  • 1
Siddhartha
  • 4,296
  • 6
  • 44
  • 65