Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List's remove method is raw

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?

like image 364
cmn Avatar asked Sep 12 '12 07:09

cmn


People also ask

How does list Remove work?

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.

How do you delete a list in Java?

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.

How do I remove an element from a collection in Java?

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.


1 Answers

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.

like image 183
Denys Séguret Avatar answered Oct 14 '22 00:10

Denys Séguret