• 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

Mixing objects using Java 5+ Generics

 
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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"));
 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How about this?
 
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, that works. Thank you both
 
reply
    Bookmark Topic Watch Topic
  • New Topic