File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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 Customer Requirements for Developers this week in the Jobs Discussion 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: 392
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: 3905
    
  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: 392
Yes, that works. Thank you both
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Mixing objects using Java 5+ Generics
 
It's not a secret anymore!