java - 如何返回对象的 ArrayList

标签 java object arraylist

我在名为 Room 的类中有一个 ArrayList,其中包含 Character 对象。我希望能够打印出一份描述,其中给出房间中的角色列表。我在字符类中创建了一个 toString 方法,该方法将返回字符的名称,但无法使其在 Room 类中工作。我对编程相当陌生,并且仍在使用数组,任何帮助将不胜感激!

这里是 addCharacter 方法,它将一个字符添加到 Room 数组列表中。

 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(' ');
    }
}

关于java - 如何返回对象的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54774407/

相关文章:

java - 使用两个 try-catch?

java - Hibernate 将 NULL 值粘贴到列表中

c# - c#中的对象克隆

c# - 在 ASP.NET 中使用Where子句

java - 使用另一个类的 getter 方法中的值

java - 使用 setString() 从 String 转换为 Clob 不起作用

java - 如何将类作为函数参数传递

javascript - 为什么 javascript 对象属性描述符不总是默认为 false (根据规范)

java - Vector 与 ArrayList 哪个更好?

java - 什么是NullPointerException,我该如何解决?