Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a toString method for an ArrayList of objects?

Tags:

java

arraylist

I am tasked with creating a toString() method for each and every object in an ArrayList. I have no idea how to go about doing this. This is the class with the ArrayList

public class DogManager {
    private ArrayList<Dog> dogList;

    public DogManager() {
        this.dogList = new ArrayList<Dog>();
    }

    public void addDog(String nameOfDog) {
        this.dogList.add(new Dog(nameOfDog));
    }

    public String toString() {
        String results = "+";
        for (int i = 0; i < this.dogList.size(); i++) {
            results += " " + this.dogList.get(i);
        }
        return results;
    }
}

I know the toString() is wrong, but I can't figure out how to make it return a description for each of the objects in that list.

like image 569
user3241721 Avatar asked Mar 20 '23 09:03

user3241721


1 Answers

You are close. The easiest way I can think of is to also implement toString() for Dog. Then in your DogManager class you can loop through each Dog and call its toString().

ie:

public String toString() {
    String results = "+";
    for(Dog d : dogList) {
        results += d.toString(); //if you implement toString() for Dog then it will be added here
    }
    return results;
  }
}

edit: You can also format it however you like. I notice some answers separate each Dog by ","

like image 171
telkins Avatar answered Apr 06 '23 23:04

telkins