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

Generic types

 
O Joseph
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
is it possible to use generic types for a vector that stores different objects e.g. other vectors and Color?
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would have to make the List's type a common base type. In the case of Color and Vector, it would be Object
 
O Joseph
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have tried that but the compiler complains they are incompatible types
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Works for me:
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're referring to not having to cast to/from the Object then no. In order to use generics they must have a common type and casting to/from that type is the only thing you can avoid. I.e. You can't do Color c = vector.get(1) with a Vector<Object>. All the compiler knows is that the Vector contains Objects, you have to do the down cast yourself.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jo Onibokun:
I have tried that but the compiler complains they are incompatible types


Can you please post the code and compiler error? We can only guess what your problem is without these details.

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic