• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What can i do and don't with this collection declaration ?

 
Faber Siagian
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What can i do and can't be done with the following collection declarations ?

1. List<MyClass> list = new ArrayList();
2. List list2 = new ArrayList<String>();


Thanks.
 
Ralph Jaus
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
list is type save, so you can can add directly only elements of type MyClass and the compiler warns you if there is a possiblility, that list gets an elements of a different type; in fact line 1 itself will produce a compiler warning).

list2 isn't type save and can contain elements of every type.
 
Faber Siagian
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If i add elements into list2 like shown below :



what happen to object referred by list2 ? i have added three different objects into it, but list2 actually is an String type-safe ArrayList.
 
Ralph Jaus
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
list2 actually is an String type-safe ArrayList.
No, the reference type counts here and that's "List".

Note: Generics are a compile time issue. After compilation, list2 refers to an usual Arraylist without any type restrictions (this is called "type erasure"). By the way, it's interesting to watch the compiled code using a decompiler when generics come into play. In your samples it would look like

List list = new ArrayList();
List list2 = new ArrayList();
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ralph Jaus:
list is type save, so you can can add directly only elements of type MyClass and the compiler warns you if there is a possiblility, that list gets an elements of a different type; in fact line 1 itself will produce a compiler warning).

list2 isn't type save and can contain elements of every type.


Adding a little to what Ralph said ...
That was adding part ... while retrieving data back ...
you will get object of type Object from list2 as it is not type safe. you will have to type cast it to MyClass or whatever you stored in that order

Whereas for list, you will get a MyClass object you need not explicitly cast it
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic