• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with Generics  RSS feed

 
leroy tsruya
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this following code:



is there a way to have a method in MyCollection class, that will return an ArrayList Object which holds only Informative Objects?
since all Objects could be stored in that class are only extends of Informatve.

Thanks
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
leroy tsruya wrote:is there a way to have a method in MyCollection class, that will return an ArrayList Object which holds only Informative Objects?
since all Objects could be stored in that class are only extends of Informatve.


Your best option would be to create a List<Informative>, and (shallow) copy all the elements over from List<T>.... Don't cast the List, as even though all the elements are indeed IS-A informative, a List<T> and List<Informative> is not the same thing.

Henry
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would this be OK?

public ArrayList<? extends Informative> getlist(){
 
leroy tsruya
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wow, thaks for the super fast replays!

@Ernest Friedman-Hill
public ArrayList<? extends Informative> getlist(){
won't this return a list of the type stored in the ArrayList? i try to return only a list of Informative Objects.

@Henry Wong, what do you mean by shallow copy?
Thanks again!
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will return a list of a subclass of Informative. Java deliberately makes the following assignment illegal (and this is basically what you're trying to do



This is deliberately illegal because if it were allowed, you could say



and then later someone could find that X when they were looking for a T. Does this make sense?

 
leroy tsruya
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
actually i want only a list of Informative.
not all extends of that class.

**edited

how do i shallow copy my List?

Thanks a lot for your time!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!