aspose file tools
The moose likes Beginning Java and the fly likes Problem when creating a list with generics. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Problem when creating a list with generics." Watch "Problem when creating a list with generics." New topic
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Problem when creating a list with generics.
 
Similar Threads
Question on Generics
Generics Help please !
Problems with Lists
The use of ? extends
SCJP Sun Certified Programmer for Java 6 Study Guide by Kathy Sierra & Bert Bates - Page 622