GeeCON Prague 2014*
The moose likes Java in General and the fly likes generics vs arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "generics vs arrays" Watch "generics vs arrays" New topic
Author

generics vs arrays

Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30595
    
154

This code compiles and gives a runtime error:


This code gives a compiler error:


I understand why the later doesn't compile - someone could add a Collection to genericsCollection which could not be stored in genericsArrayList. As far as I can tell, this is the same concept used in the array example - someone can store a vector in the collectionArray which arrayList cannot handle. I think these two examples are logically equivalent.

Are they different somehow? Is it that the array example is "legacied" in from Java 1.4 and doesn't get a compile time check?


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Jeanne]: Is it that the array example is "legacied" in from Java 1.4 and doesn't get a compile time check?

Yes, that's it. Basically Sun screwed up the original rules for array references, making them a bit too permissive on type checking in some circumstances. But they won't change that now for backward compatibility. Instead they just went ahead and used different rules for generics, and now encourage the use of generic collections in place of arrays.
[ April 23, 2008: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30595
    
154

Thanks Jim. Not only did you confirm my suspicions, but you added something i didn't even think to ask!
and now encourage the use of generic collections in place of arrays.
 
GeeCON Prague 2014
 
subject: generics vs arrays