• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

generic gotcha's

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have been looking at Generics this week and I found this great article on Generic gotcha's. It also has some excellent links to a couple of really good free (woohoo) generic pdf tutorial and FAQ, both of which are good resources for learning about the tough topic of generics.

one of the biggest Generic Gotcha's is Generics are not covariant. Which means you can't put a subclass into a collection which specify's the superclass. The reason this is a gotcha because the rest of Java is covariant but I think once you understand the reasons for it, it makes sense.

I think the biggest Gotcha in Generics is the wierd placing of the unusual looking angled brackets, I have said it before but it looks a bit of a hack job. Not that I'm saying I don't think it is a good addition, I do, it just looks wierd.

a link to my blog with the link to the Generic Gotcha's article
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"Which means you can't put a subclass into a collection which specify's the superclass."

You mean you cannot do the following?



If so, try it.
[ May 04, 2006: Message edited by: Barry Gaunt ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Arrays are covariant, which means that because Integer is a subclass of Number, then Integer[] is a subclass of Number[]. So whereever a Number[] is expected we can use an Integer[].
An ArrayList is not covariant, because ArrayList<Integer> is not a subclass of ArrayList<Number>, even if Integer is a subclass of Number. In this case, if an ArrayList<Number> is required, then we cannot offer to use an ArrayList<Integer>.
[ May 04, 2006: Message edited by: Barry Gaunt ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic