【问题标题】:Is there a way to add the same object to ArrayList, but with changed values without re-writing the other elements of ArrayList?有没有办法将相同的对象添加到 ArrayList,但更改了值而不重写 ArrayList 的其他元素?
【发布时间】:2020-08-27 19:56:31
【问题描述】:

我有一个名为 CanvasState 的类,它包含两个 2D 数组和一个静态 ArrayList。

public class CanvasState {

private int [][] colorArray;
private boolean [][] boolArray;
private static List<CanvasState> listState = new ArrayList<>();

public CanvasState(int [][] colorArray, boolean [][] boolArray){
    this.colorArray = colorArray;
    this.boolArray = boolArray;
}
public void addToArrayList(CanvasState canvasState){
   listState.add(canvasState);
}

}

所以每当画布被绘制并且用户抬起手指时,我都会保存状态。(这是在另一个类中)

if(event.getAction() == MotionEvent.ACTION_UP){
   canvasState = new CanvasState(colors, cellChecked);
   canvasState.addToArrayList(canvasState);
}

我期望得到一个 CanvasStates 的 ArrayList 来保存我的 2D 数组及其调整后的值,但似乎虽然在每个 ACTION_UP 上创建了一个新的 CanvasState 对象,但每个 CanvasObject 都被重新编写,因此两个数组对于ArrayList 中的所有对象。有没有办法解决?或者 ArrayList 不适合这个?

【问题讨论】:

  • 假设触发不同的ACTION_UP时colors和cellChecked是不同的,那么为什么两个数组是一样的呢?

标签: java android arrays arraylist


【解决方案1】:

问题在于您的 CanvasState 对象都引用了相同的二维数组(colorArray 和 boolArray)。

您需要在构造函数中复制这些数组的当前状态。

public CanvasState(int [][] colorArray, boolean [][] boolArray){        
  this.colorArray = copy2D(colorArray);
  this.boolArray = copy2D(boolArray);
}

使用这些实用方法(或您选择的其他方法来克隆二维数组):

static int[][] copy2D(int[][] arr)
{
    int[][] narr = new int[arr.length][];
    for(int i=0; i<arr.length; i++)
        narr[i] = arr[i].clone();
    return narr;
}

static boolean[][] copy2D(boolean[][] arr)
{
    boolean[][] narr = new boolean[arr.length][];
    for(int i=0; i<arr.length; i++)
        narr[i] = arr[i].clone();
    return narr;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2015-08-19
    • 2011-07-25
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多