java - 如何返回对象的 ArrayList
问题描述
我在一个名为 Room 的类中有一个 ArrayList,其中包含 Character 对象。我希望能够打印出一个描述,该描述将给出房间中的角色列表。我在字符类中创建了一个 toString 方法,该方法将返回字符的名称,但无法从 Room 类中使用它。我对编程相当陌生,并且仍在使用数组,任何帮助将不胜感激!
这是将字符添加到 Room 数组列表的 addCharacter 方法。
public void addCharacter(Character c)
{
assert c != null : "Room.addCharacter has null character";
charInRoom++;
charList.add(c);
System.out.println(charList);
// TO DO
}
这是我用来打印房间中字符列表的 getLongDescription() 类。(这是我遇到问题的方法)。
public String getLongDescription()
{
return "You are " + description + ".\n" + getExitString()
+ "\n" + charList[].Character.toString; // TO EXTEND
}
这是 Character 类中的 toString 方法。这种方法有效。
public String toString()
{
//If not null (the character has an item), character
//and item description will be printed.
if(charItem != null){
return charDescription +" having the item " + charItem.toString();
}
//Otherwise just print character description.
else {
return charDescription;
}
}
解决方案
由于您正在使用List<Character>
,并且您已经实现了自定义toString
方法,因此您只需调用characters.toString()
.
public String getLongDescription() {
return "You are " + description + ".\n" + getExitString()
+ "\n" + characters; // toString implicitly called.
}
该ArrayList#toString
方法将简单地调用每个元素的toString
.
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next(); // Get the element
sb.append(e == this ? "(this Collection)" : e); // Implicit call to toString
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
推荐阅读
- c# - 如何比较将两者都转换为 Enum 的对象和整数值?
- python - 如何使用python绘制一个条形图,每个条形都有不同的类别?
- web-scraping - 我想要链接和每个链接的所有内容
- python - 检查指令集 tensorflow build 是用
- r - 为什么输出在不同的运行中具有不同的列顺序?
- python - 可以同时运行 2 个 for 循环,一个接一个地循环吗?
- ember.js - Ember - 禁用原型扩展
- io - 如何在 Rust 中一次读取和处理 N 行文件?
- javascript - 如何在返回之前格式化json数组中的所有电话号码
- react-native - 如何在 React Native 0.55 CLI 或更高版本中调整屏幕亮度?