如何为对象的ArrayList创建toString方法?

编程入门 行业动态 更新时间:2024-10-27 16:23:21
本文介绍了如何为对象的ArrayList创建toString方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的任务是为ArrayList中的每个对象创建一个toString()方法.我不知道该怎么做.这是带有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; } }

我知道toString()是错误的,但是我不知道如何使它返回该列表中每个对象的描述.

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.

推荐答案

您很亲密.我能想到的最简单的方法是同时为Dog实现toString().然后,在您的DogManager类中,您可以遍历每个Dog并调用其toString().

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().

即:

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

更多推荐

如何为对象的ArrayList创建toString方法?

本文发布于:2023-11-04 00:34:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:何为   对象   方法   ArrayList   toString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!