This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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: 32481
    
214

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?


[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, 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: 32481
    
214

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.
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: generics vs arrays
 
It's not a secret anymore!