• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mixing objects using Java 5+ Generics

 
M Burke
Ranch Hand
Posts: 406
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way I can define a List and add objects of different types?

Here is the old way...

List params = new LinkedList();
params.add(new Integer(1));
params.add(new String("A"));
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about this?
 
Stephan van Hulst
Bartender
Posts: 6318
78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
M Burke wrote:Is there a way I can define a List and add objects of different types?

Here is the old way...

List params = new LinkedList();
params.add(new Integer(1));
params.add(new String("A"));

Seetharaman's answer is correct. I would however like to draw your attention to something else, namely the use of new Integer(1) and new String("A");

Don't do this. Use literals instead. Not only is it easier to read, but this way the platform can use interned values (values that may already exist in memory). Don't create new Objects when it's not necessary.
 
M Burke
Ranch Hand
Posts: 406
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that works. Thank you both
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic