Now blogging at diego's weblog. See you over there!

add(E), but remove(Object)?

Martin notes that in Java 5, the new-super-shiny-generics-enabled Collection interface has some inconsistencies. Most notably, the add method is dependent on the specific type for the collection, while remove and contains (most notably) are not. Here are the method contracts:

boolean add(E o)
boolean remove(Object o)
boolean contains(Object o)
Martin wonders why the discrepancy. I see two options.

Option one is a hilarious story that involves a monkey, a pantsuit, and a cherry cake interfering with the programmer's work and making her/him commit the grievous error for which she/he will feel regret the rest of her/his days. Let's call this the low-probability option.

Option two is that the Architecture Astronauts involved in the spec were carried away by the following definition of the remove method :

Removes a single instance of the specified element from this collection, if it is present (optional operation). More formally, removes an element e such that (o==null ? e==null : o.equals(e)), if this collection contains one or more such elements. Returns true if this collection contained the specified element (or equivalently, if this collection changed as a result of the call).
and this one from the contains method:
Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).
My theory (and hoyven mayven, this is a theory only!) is that because the formal definition involves the use of the equals method and the method specifies an Object (and cannot, given that is the class at the top of the Java object hierarchy, know anything about "E") then the contract for contains and remove also follows with Object rather than E.

Sounds reasonable?

If anyone has the skinny on this, please pass it on. Alternative theories will also be appreciated. Especially if they involve monkeys (monkey-butlers are also accepted).

Posted by diego on February 7 2005 at 10:23 PM

Copyright © Diego Doval 2002-2011.
Powered by
Movable Type 4.37