• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

print subclasses arraylists

 
Ricardo Soares
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two classes ( subclass1 and subclass2 ) which both inherit from superclassA and have created two ArrayLists, one that holds objects from subclass1 and the other one holds objects of subclass2.

I have two methods in another class thats receives each list and prints its elements:


this works fine but i was thinking as they both derive from the same superclass couldn't i do something more generic instead of having two different methods ?


when i do it like this im told to either change the type of my List or the type that goes into the method

appreciate any help
 
Rob Spoor
Sheriff
Pie
Posts: 20613
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That will almost work. I say almost because, although subclass1 IS-A superclassA, the same cannot be said of List<subclass1> and List<superclassA>. But fortunately, wildcards can help you out:
And you should consider using a for-each loop if you don't need the Iterator inside the loop:
 
Ricardo Soares
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
worked fantastically, thank you
 
Rob Spoor
Sheriff
Pie
Posts: 20613
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic