• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics ArrayList

 
kri shan
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
Posts: 147
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
kri shan
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 147
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 147
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know AutoBoxing/unBoxing, I asked why is that statement here?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic