aspose file tools*
The moose likes Beginning Java and the fly likes print subclasses arraylists Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "print subclasses arraylists" Watch "print subclasses arraylists" New topic
Author

print subclasses arraylists

Ricardo Soares
Greenhorn

Joined: Nov 27, 2012
Posts: 9
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

Joined: Oct 27, 2005
Posts: 19761
    
  20

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ricardo Soares
Greenhorn

Joined: Nov 27, 2012
Posts: 9
worked fantastically, thank you
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19761
    
  20

You're welcome
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: print subclasses arraylists