wood burning stoves*
The moose likes Beginning Java and the fly likes Generics ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics ArrayList" Watch "Generics ArrayList" New topic
Author

Generics ArrayList

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1382



Normally ArrayList storage are used for hetrogenous values than Arrays. If i use Generics then ArrayList supports homogeneous same as Arrays. How can i store hetrogenous values in ArrayList usign Generics?
Jan Hoppmann
Ranch Hand

Joined: Jul 19, 2010
Posts: 147

While using Generics, you can't. That is the whole point, so you have type safety and don't have to worry if the saved object is of the right type. Use a List without a given Type (or <Object>) to save heterogenous values, but you have to typecast when you read them.


Life is full of choices. Sometimes you make the good ones, and sometimes you have to kill all the witnesses.
kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1382
List<Object> list = new ArrayList<Object>();
list.add(sel);
list .add("adsf");

Is it correct?

Java5 autoboxing/unboxing feature avoids specific casting for each type.
Jan Hoppmann
Ranch Hand

Joined: Jul 19, 2010
Posts: 147

Autoboxing/unboxing works only for primitive types and their wrappers, if the VM knows your list returns an Object, it will treat it as an Object. You will have to cast to use the items in the list properly.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

kri shan wrote:List<Object> list = new ArrayList<Object>();
list.add(sel);
list .add("adsf");

Is it correct?

It's correct, but when you retrieve some thing from this ArrayList, there may be ClassCastException, because, you stored different objects!
kri shan wrote:
Java5 autoboxing/unboxing feature avoids specific casting for each type.

What do you mean?
Jan Hoppmann
Ranch Hand

Joined: Jul 19, 2010
Posts: 147

Abimaran Kugathasan wrote:
kri shan wrote:
Java5 autoboxing/unboxing feature avoids specific casting for each type.

What do you mean?


Autoboxing and auto unboxing means that you are able to cast from Integer to int, Long to long, and generally from the primitive types to their wrappers and back. But this only works for primitive types / their wrappers, not for Object objects.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

I know AutoBoxing/unBoxing, I asked why is that statement here?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics ArrayList