February 07, 2005
Martin spotted a
few inconsistencies in the new Generic Collections and wonders why...
But a couple of aspects of the new generics-enabled collections framework
annoy me. For example, the Collections interface is declared as
Collection<E> and the
add method, for example, is
correctly declared as:
boolean add(E object)
So I cannot help but wonder why, then, is
remove declared as:
boolean remove(Object object)
Similarly, the toArray() method should be declared as follows:
Rest assured, this is not an oversight, these methods were designed this way
for two very good reasons.
Can you see why?
Here are hints if you get stumped (in white):
- Existing 1.4 code would break with this definition.
- Try to implement this method for all Collections.
Posted by cedric at February 7, 2005 10:27 PM
Cedric, URL in post has "mailto:" protocol
More on this and many other issues with generics http://www-106.ibm.com/developerworks/java/library/j-jtp01255.html
Sorry for offtopic...
Why you have a name OTAKU? Do u have jap. origins?
I believe it just doesn't matter what type you use on the 'remove' signature. It's valid to try to remove objects that are not in the collection, so what additional safety do you gain from restricting the type of the remove parameter?
> so what additional safety do you gain from
> restricting the type of the remove parameter?
To catch brain-farts. I could easily imagine typos (or copied code) that removes the wrong object from a Collection. The static checks could catch most of those problems.
Kyle: It'd restrict the use of wildc?rds in collection generic parameters. I ought to be able to remove an object from a collection, even if the exact type parameter type is unknown.
Something does irritates me, however. Although there is a common idiom that a key that maps to null in a Map is the same as checking if the map contains the key, I can still place null values in a Map if I so wish (given a suitable implementation). But try putting nulls in a Queue. What's the difference?