• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem when creating a list with generics.  RSS feed

 
Buddhika Mawella
Ranch Hand
Posts: 40
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Pramod P Deore
Ranch Hand
Posts: 633
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Buddhika Mawella
Ranch Hand
Posts: 40
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can still add null, but nothing else.
 
Buddhika Mawella
Ranch Hand
Posts: 40
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 436
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, thanks mate.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!