How do I create a toString method for an ArrayList

2020-07-18 09:27发布

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.

6条回答
Bombasti
2楼-- · 2020-07-18 10:06

I would do something like this, no need to loop through the list of dogs (a List.toString already does that for you).

public class Dog {
    private String name;

    @Override
    public String toString() {
        return "Dog{" + name + "}";
    }
}


public class DogManager {
    private List<Dog> dogs;

    @Override
    public String toString() {
        return "DogManager{dogs=" + dogs + "}";
    }
}
查看更多
等我变得足够好
3楼-- · 2020-07-18 10:11
public String toString() {
    String results = "";
    for(Dog d : dogList) {
        results += "," + d.toString();
    }
    return results;
  }
}
查看更多
再贱就再见
4楼-- · 2020-07-18 10:20

An arraylist is a dynamic array filled with Objects. Why don't you overwrite the toString method in the Dog class.

查看更多
老娘就宠你
5楼-- · 2020-07-18 10:21

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 ","

查看更多
啃猪蹄的小仙女
6楼-- · 2020-07-18 10:23
public String toString(){
    String toReturn = "[";

    for(Dog currentDog: dogList){
        toReturn+=currentDog.toString()+",";
    } 
    toReturn = toReturn.substring(0,toReturn.length()-1);

    return toReturn+"]";
}
查看更多
冷血范
7楼-- · 2020-07-18 10:27

You need to define .toString() method in your Dog class and make it override the default .toString() method of Object class.

public class Dog {

String name;
String age;
String race;

@Override
public String toString() {

    return String.format("Name: %s, Age: %s, Race: %s", name, age, race);
}
}

Then you can simply call System.out.println(dog) for each element of the array and your custom text defined in dog's .toString() method will be displayed.

查看更多
登录 后发表回答