File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generics vs arrays

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 33671
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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 ]
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 33671
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic