【问题标题】:How To Return An ArrayList Of Objects如何返回对象的 ArrayList
【发布时间】:2019-02-19 20:27:30
【问题描述】:

我在一个名为 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;
    }

}

【问题讨论】:

标签: java object arraylist


【解决方案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(' ');
    }
}

【讨论】:

  • 我不确定在此处包含 ArrayList 的 toString 方法的所有代码是否会对初学者有所帮助。它可能会造成更多的混乱。当然,我可能是错的。
  • @DavidConrad 你是对的,大卫。我在“重要”行附近添加了几个 cmets。无论如何,如果他/她有问题,我会在这里回答。
  • 有没有办法通过不改变 toString 函数来做到这一点,因为这是一个赋值,我不能改变这个函数。
  • @ol1ie310 哪个 toString?属于哪一班?
  • @ol1ie310 如果您的意思是我在上面发布的方法,它是 ArrayList 的标准方法。您无需编写或编辑任何内容。
猜你喜欢
  • 2014-04-03
  • 2020-07-03
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 2019-02-20
  • 2015-11-15
  • 2017-10-23
相关资源
最近更新 更多