如何返回对象的ArrayList

问题描述 投票:0回答:1

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

这是addCharacter方法,它为Room arraylist添加一个字符。

 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;
    }

}
java object arraylist
1个回答
1
投票

当你使用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(' ');
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.