首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何返回对象的ArrayList

如何返回对象的ArrayList
EN

Stack Overflow用户
提问于 2019-02-20 04:27:30
回答 1查看 101关注 0票数 0

我在一个名为Room的类中有一个包含Character对象的ArrayList。我希望能够打印出一个描述,将给出一个房间中的字符列表。我在character类中创建了一个toString方法,该方法将返回字符的名称,但无法从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;
    }

}
EN

回答 1

Stack Overflow用户

发布于 2019-02-20 04:33:36

因为您正在使用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(' ');
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54774407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档