在给定的行和col位置设置给定元素

时间:2015-09-06 22:50:03

标签: java

我有2D ArrayList和方法public void set(int row, int col, T x),可将this.element更改为x。当我尝试运行我的代码时它会给我java.lang.ArrayIndexOutOfBoundsException而我不明白为什么因为我已经初始化了我的代码:

Board board = new Board(-2,3,-4,3,"xxx");

其中构造函数值为

new Board(int minRow, int maxRow, int minCol, int maxCol, T e)

java.lang.ArrayIndexOutOfBoundsException发生在行中的set()方法中:

if(myBoard.get(row).get(col).equals(this.element))

为什么我会收到该错误?我是否正确访问ArrayList中的行和列号?

我的toString()代表

3 个答案:

答案 0 :(得分:1)

执行board.set(-1, 0, "A");时,您尝试访问ArrayList索引-1处的元素。 row中的set()为-1,您基本上会在myBoard.get(-1)语句中调用if

您需要记住ArrayList在索引方面是基于0的。要解决此问题,请从-1减去最小索引以获取正确的索引。这也适用于列索引。例如,给定

Board board = new Board(-2,3,-4,3,"xxx");

你需要做

int row = (-1) - (-2);     //row you want - lowest row (row at index 0 in the ArrayList)
int col = (0) - (-4);      //col you want - lowest col (col at index 0 in the ArrayList)
board.set(row, col, "A");

答案 1 :(得分:1)

负索引对于Java中的所有有序数据结构都是无效的。你的Board类应该将索引重写为正数,以隐藏调用者的这个时髦逻辑:

public void set(int virtualRow, int virtualCol, T x) {
    int row = translateIndex(minRow, virtualRow, maxRow);
    int col = translateIndex(minCol, virtualCol, maxCol);

    // this.expandToInclude(row, col);
    if (myBoard.get(row).get(col).equals(this.element)) {
        myBoard.get(row).set(col, x);
        RowColStack<T> temp = new RowColStack<T>(row, col, x);
        undoStack.add(temp);
    }
}

private int translateIndex(int min, int index, int max) {
    if (index< min || row > max) throw new ArrayOutOfBoundException();
    return index - min;
}

答案 2 :(得分:0)

几点意见:

  1. 一旦你知道了电路板的尺寸(在程序执行期间似乎没有变化),使用2D阵列而不是ArrayList可能会简单得多。
  2. 您不是在初始化中在数组列表中创建元素。所以实际上你有一个0x0数组,并且对于任何get调用都将接收java.lang.ArrayIndexOutOfBoundsException
  3. 您当然可以接收负面索引,但在访问元素之前将它们转换为数组/ arraylist中的正确索引,如其他答案中所述。
  4. 您可以使用类似于以下的逻辑初始化数组列表:

    for(int i = 0; i < nRows; i++) {
       rowList = new ArrayList();
       myboard.add(rowList); 
       for(int j = 0; j < nCols; j++)
          rowList.add(null);
       }
    }
    

    将此视为伪代码,并以此为基础。

相关问题