| Author |
Problem when creating a list with generics.
|
Buddhika Mawella
Ranch Hand
Joined: Jan 06, 2011
Posts: 36
|
|
Hi falks,
Please note that there is a class called Dog that extends another class Called Animal.
if I create a ArrayList as below, That shows a compilation error at line 2. What is the reason for that?
Thanks.
|
BM
|
 |
Pramod P Deore
Ranch Hand
Joined: Jul 15, 2008
Posts: 629
|
|
|
what if suppose you are working on big project and someone put Horse object inside this list then? because he knows Horse extends Animal (suppose class Horse extends from Animal ). Generics is use for compile time protection. And you may think that you have a list which contains only dog.
|
Life is easy because we write the source code.....
|
 |
Buddhika Mawella
Ranch Hand
Joined: Jan 06, 2011
Posts: 36
|
|
That means just after I assigning my list of dogs to List<? extends Animal> list,
That list becomes read only. I mean we cant add Dogs,Horse or Animals into list. Am I correct?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
You can still add null, but nothing else.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Buddhika Mawella
Ranch Hand
Joined: Jan 06, 2011
Posts: 36
|
|
|
But still I feels like its unfair. Because when I am creating my list I am initializing it as, new ArrayList<Dog>(); which says I am creating an array list that can hold Dog objects.Then why cant I add Dog objects?
|
 |
Hauke Ingmar Schmidt
Rancher
Joined: Nov 18, 2008
Posts: 371
|
|
Buddhika Mawella wrote:But still I feels like its unfair. Because when I am creating my list I am initializing it as, new ArrayList<Dog>(); which says I am creating an array list that can hold Dog objects.Then why cant I add Dog objects?
Because your variable does not tell this. The type check is done on the type of the variable, not the type of the object. If you don't tell the compiler that you hold a list of dogs, it doesn't know this.
|
 |
Buddhika Mawella
Ranch Hand
Joined: Jan 06, 2011
Posts: 36
|
|
|
Okay, thanks mate.
|
 |
 |
|
|
subject: Problem when creating a list with generics.
|
|
|