如何在ArrayList中存储已完成的历史记录

时间:2016-09-18 07:39:37

标签: java

假设我是从GUI Jtextfield

存储的

2d6并使用拆分字符串并将2和6保存在单独的arraylists中。然后检索两个数字并创建一个循环

for(i=2;i<=6,i++){
    data.add(i); //data is another arraylist
}

[2,3,4,5,6,7,8,9,10,11,12]     // values stored in an arraylist

现在,如果我从数据中删除了2和3(Arraylist)[4,5,6,7,8,9,10,11,12]

现在我再次使用另一个字符串&#34; 3d8&#34;并继续相同的过程

现在,如果我再次输入数字&#34; 2d6&#34; 如何记住历史记录并在打印时显示此值[4,5,6,7,8,9,10,11,12] 而不是这个值

[2,3,4,5,6,7,8,9,10,11,12]

1 个答案:

答案 0 :(得分:0)

对于这个特定的程序,你继续使用从文本中提取的两个数字做同样的事情,我建议你使用第三个ArrayList名为hist的名称n存储每对数字步。我们假设您要存储History步骤的历史记录,以便重做。我将使用名为class History{ int a, b; History(int a, int b){ this.a=a; this.b=b; } } 的类和数据成员来存储这两个数字。

public static void main(String[] args){
    ArrayList<History> hist = new ArrayList<History>(n);
    //int a,b store the two numbers from the text
    ...
    //adding the step to the history list
    if(hist.size() < n)
        hist.add(new History(a,b));
    else{
        //shift every element to the left
        //and add new history in the end
        //since hist's capacity = n
    }
}

现在在你的主要班级......

int s

如果hist.get(s-1)表示步骤编号,则ArrayDeque返回存储该步骤的数字对的对象。这可以帮助。这是一种简单的方法。

@Ole V.V.提出了一个很好的建议。更优选的方法是,如果您遇到步数限制的情况,请使用ArrayDeque java.util包中存在main() 39;手动必须键入用于移动元素的代码并使用类方法。在这种情况下,ArrayDeque<History> hist = new ArrayDeque<History>(n); ... //adding the pairs if(hist.size() == n) hist.removeFirst(); hist.addLast(new History(a,b)); 中的代码变为

{{1}}
相关问题