aspose file tools*
The moose likes Java in General and the fly likes Mixing objects using Java 5+ Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Mixing objects using Java 5+ Generics" Watch "Mixing objects using Java 5+ Generics" New topic
Author

Mixing objects using Java 5+ Generics

M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 388
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

Joined: Jan 28, 2008
Posts: 5575

How about this?
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

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

Joined: Jun 25, 2004
Posts: 388
Yes, that works. Thank you both
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Mixing objects using Java 5+ Generics