Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generics vs arrays

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34837
369
Eclipse IDE Java VI Editor
  • 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
  • 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: 34837
369
Eclipse IDE Java VI Editor
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic