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
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: 396
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: 4087
    
  18

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.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 396
Yes, that works. Thank you both
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Mixing objects using Java 5+ Generics
 
It's not a secret anymore!