Hussein Reda AlBehary Hussein Reda AlBehary - 3 months ago 19
Java Question

Print ArrayList Object

I have created several objects and I want to print only one parameter of the objects in ArrayList:

Superhero batman = new Superhero("Bruce", 26, "Batman");
Human rachel = new Human("Rachel", 24);

Superhero ironman = new Superhero("Tony", 35, "Ironman");
Human pepper = new Human("Pepper", 22);

List<Human> people = new ArrayList<Human>();
people.add(batman);
people.add(rachel);
people.add(ironman);
people.add(pepper);


I want to print:

Bruce
Rachel
Tony
Pepper

Answer
for(Human human : people) {
    System.out.println(human.getName());
}

This should print name for each human in people list. You should have method in Human class:

getName() {
    return this.name;
}