The question says it all..
From List's code:
Add method:
public boolean add(E e) { ... }
Whereas, remove method:
public boolean remove(Object o) { .. }
Is there any specific reason for this?
Removes the first occurrence of the specified element from given list, if the element is present. If the element is not present, the given list is not changed. After removing, it shifts subsequent elements(if any) to left and decreases their indexes by 1.
The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it justs removes all of the elements from the List.
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.
From the javadoc :
If this list does not contain the element, it is unchanged
So adding a type constraint here would be simply useless, while the constraint on add
ensures at compile time the list contains what is written on the box.
Note that there is some liberty for implementation as the method is allowed to throw a
ClassCastException if the type of the specified element is incompatible with this list (optional)
The ArrayList implementation doesn't throw this exception :
439 public boolean remove(Object o) {
440 if (o == null) {
441 for (int index = 0; index < size; index++)
442 if (elementData[index] == null) {
443 fastRemove(index);
444 return true;
445 }
446 } else {
447 for (int index = 0; index < size; index++)
448 if (o.equals(elementData[index])) {
449 fastRemove(index);
450 return true;
451 }
452 }
453 return false;
454 }
This means you don't have to check the class of raw objects before you do the remove operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With