February 07, 2005

Collection.toArray() quiz

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)

and

Similarly, the toArray() method should be declared as follows:
    E[] toArray()
Instead of:
    Object[] toArray()

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):

  1. Existing 1.4 code would break with this definition.
  2. Try to implement this method for all Collections.

 

Posted by cedric at February 7, 2005 10:27 PM
Comments

Cedric, URL in post has "mailto:" protocol

Posted by: Reader at February 8, 2005 02:50 AM

More on this and many other issues with generics http://www-106.ibm.com/developerworks/java/library/j-jtp01255.html

Posted by: Valery Silaev at February 8, 2005 02:52 AM

Sorry for offtopic...

Why you have a name OTAKU? Do u have jap. origins?

Posted by: toku at February 9, 2005 12:02 AM

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?

Posted by: thefrog at February 9, 2005 02:44 AM

> 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.

Posted by: Kyle Lahnakoski at February 9, 2005 05:36 AM

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?

Posted by: Tom Hawtin at February 9, 2005 01:05 PM

big thank

Posted by: fungus toenail treatment at September 28, 2006 08:18 AM
Post a comment






Remember personal info?