【问题标题】:How to print out an ArrayList in the order it was added如何按添加顺序打印出 ArrayList
【发布时间】:2015-05-14 09:32:25
【问题描述】:

在我的程序中调用 record() 方法。所以如果用户输入 1、2、3、4、5、6、7。按此顺序,它会打印出 7、6、5、4、3、2、1。我尝试了增强的 for 循环、递增的 for 循环等。请帮助,提前谢谢。

ArrayList<Integer> playerMoves = new ArrayList<Integer>(20); 

    public void record(int value) {

    playerMoves.add(0, value);

    if(playerMoves.size() > 20) {
        playerMoves.remove(playerMoves.size() - 1);
    }
}


public void displayPlayerMoves() {

    int fullstopCount = 20;
    System.out.print(playerMoves.size() + " moves: ");

    for(int i = playerMoves.size(); i > 0; i--) {
        fullstopCount--;
        if(playerMoves.size() == fullstopCount) {
            System.out.print(playerMoves.get(i) + ".");
        } else {
            System.out.print(playerMoves.get(i) + ", ");
        }
    }


}

【问题讨论】:

  • 你正在使用fullstopCount 它被初始化为0 然后你正在使用fullstopCount-- 为什么?您还需要将add 方法更改为playerMoves.add(value);

标签: java arrays sorting arraylist


【解决方案1】:

您正在将每个元素添加到列表的第一个位置:

playerMoves.add(0, value);

这意味着您正在创建一个顺序与插入顺序相反的列表。

如果你把它改成:

playerMoves.add(value);

它将每个元素添加到列表的末尾,这也将导致列表按插入顺序打印。

如果你做出改变,你也应该改变

if(playerMoves.size() > 20) {
    playerMoves.remove(playerMoves.size() - 1);
}

if(playerMoves.size() > 20) {
    playerMoves.remove(0);
}

因为您想删除最旧的移动。

编辑:

我刚刚注意到,当您打印元素时,您会以相反的顺序遍历列表,但是您的循环有错误的索引。应该是:

int i = playerMoves.size() - 1; i >= 0; i--)

如果您使用该循环,则不必更改 record 方法。

如果你确实改变了列表中元素的顺序,你可以简化你的显示方法:

public void displayPlayerMoves() 
{
    System.out.print(playerMoves.size() + " moves: ");
    bool first = true;
    for(int value : playerMoves) {
        if (!first)
            System.out.print(", ");
        first = false;
        System.out.print(value);
    }
    System.out.print('.');
}

【讨论】:

  • 为什么不是add(value)? otw 用的value 是什么?
  • 您是说playerMoves.add(value); 吗?
  • 仍然打印 7, 6, 5, 4, 3, 2, 1。:(
  • @AndyTurner 对不起,错字:)
  • 您还想删除元素 0,而不是最后一个,我猜,或者在 size 已经是 20 的情况下,您也可以不添加元素。
【解决方案2】:

您应该在列表末尾添加值,并从列表的开头删除旧值:

playerMoves.add(value);     
if(playerMoves.size() > 20) {
    playerMoves.remove(0);
} 

请注意,从列表的开头删除是针对ArrayListO(n) 操作;更改为 LinkedList 将是 O(1)

但如果您坚持使用ArrayList,则应在添加另一个元素之前删除第 20 个元素,因为添加第 21 个元素将导致 ArrayList 必须增加其容量。

【讨论】:

    【解决方案3】:

    您的代码有两个缺陷:

    在第一个索引处添加并以相反的顺序打印。

    将添加元素更改为:

     playerMoves.add(value);
    

    并循环打印为:

      for(int i =0; i <playerMoves.size(); i++) {
         // your code 
        }
    

    【讨论】:

      猜你喜欢
      • 2016-04-22
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      相关资源
      最近更新 更多