简体   繁体   中英

Combining array lists containing different objects in Java

im working on a small game in Java. I have an abstract class SuperHero , and the classes WaterHero and LandHero that extends from Superhero . How do I combine the two objects allHeroes and allHeroes2 in an array list? I don't want to loop though multiple array list when writing methods later.

ArrayList<WaterHero> allHeroes = new ArrayList<>();  
ArrayList<LandHero> allHeroes2 = new ArrayList<>();

allHeroes.add(new WaterHero("SharkHero", 100, 27, 13));  
allHeroes.add(new WaterHero("Fishy", 100, 30, 22));  
allHeroes2.add(new LandHero("Iron Man", 120, 25, 16));  
allHeroes2.add(new LandHero("LandBoy", 120, 25, 16));

I tried using ArrayList<Object> Heroes= new ArrayList<>(); but dont really understand how this works, and how to reach methods from SuperHero . For example i could not reach getName() in superclass SuperHero

ArrayList<Object> Heroes= new ArrayList<>()

We write variablesLikeThis and TypesLikeThis . So, heroes , not Heroes .

ArrayList<Object> means it can contain objects. And a lot of things are 'objects'. You would be allowed to stick an Integer object in there. It has no getName() method, thus, heroes.get(0).getName() won't compile. Yes, yes, you didn't put an integer in there, but the compiler doesn't know that. There is no guarantee. Java doesn't let you write code that potentially makes no sense, even if currently it always will. That's what compile-time type-checking means.

Instead you want List<SuperHero> : That is a list where every element is some sort of superhero. Could be a WaterHero instance, or a LandHero instance, as long as it's an instance of X such that X is either SuperHero or some type that extends SuperHero (or extends something that extends SuperHero - just needs to be anywhere in the type hierarchy).

Now that you've told java that, whatever might be in the list, it's all definitely superheroes, you can call methods on anything from the list that java knows, for sure , it'll have. All methods that class SuperHero has, for example - given that you said everything in the list is at least that, all of those methods are fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM