为什么二维数组中某个对象的索引返回-1?

4

我有这个方法:

public static int[][] executeRules(int[][] array){
    int rowNumber = 0;
    for(int[] row : array){

        for (int cell:row){
            int index = Arrays.asList(array).indexOf(cell);
            System.out.println(index);
            int[] surroundingCells = getSurroundingCells(index);

            int liveCells = 0;
            for(int aSurroundingCell: surroundingCells){
                if(aSurroundingCell == 1){
                    liveCells++;
                }
            }

            //If cell is dead
            if (cell == 0){


                //Bring cell back to life if condition is met (three surrounding cells alive)
                if (liveCells == 3){

                    cell = 1;
                    liveCells = 0;
                }


            }
            //If cell is alive
            else if (cell == 1){
                //If cell is underpopulated
                if (liveCells < 2){
                    cell = 0;
                }
                if (liveCells > 3){
                    cell = 1;
                }




            }else {
                System.out.println("An error has occured.");

            }

            if(index != -1){
                array [rowNumber][index] = cell;
            }
        }
        if(rowNumber < _size - 1){
            rowNumber ++;
        }

    }
    return array;
}

这是康威生命游戏,我试图测试这个二维数组中的每个“单元格”,然后更改其值并返回新的数组。但由于某种原因,第二维的索引总是返回-1。我不知道为什么。有人知道吗?


1
如果未找到该值,indexOf 将返回 -1。 - Hot Licks
在这种情况下使用 indexOf 而不是传统的 for 循环有点愚蠢。 - Hot Licks
1
你的List里有array而不是值,因为你传递了一个int[][],所以你有一个int[]列表。 - Dima Maligin
没错,那个 indexOf 没有任何机会能够工作。 - Hot Licks
@DimaMaligin找到了问题,Arrays.asList(array) 应该改为 Arrays.asList(row) - 你应该将它发布为一个答案! - Nir Alfasi
显示剩余2条评论
2个回答

2
indexOf的文档规定它返回列表中指定元素的第一个出现位置的索引,如果列表不包含该元素,则返回-1。这意味着列表不包含该元素。
你代码中的问题在于调用了asList方法,但它并没有做你想象中的事情。 asList方法将返回一个List<int[]>,但你正在搜索一个int(单元格)的索引,这是永远找不到的。
请参阅文档

1
@Squid
你的List里面有array而不是值,因为你传递了一个int [][],所以你有一个int[]的列表。
- Dima Maligin
@alfasin 编辑以提供更多细节。 - Jean-François Savard

2
for(int[] row : array){
    for (int cell:row){
        int index = Arrays.asList(array).indexOf(cell);

你可能有些混淆了行和单元格。`array`是一个二维数组,所以`indexOf()`会搜索数组的值(行),但你传递的`cell`只是一个整数。它永远无法找到等于`int[]`的整数。
在循环中使用for-each循环然后尝试扫描值来查找索引有点复杂且低效。当处理数组索引时,我强烈建议使用传统的`for`循环而不是for-each循环。
for(int rowIndex = 0; rowIndex < array.length; rowIndex++) {
    int[] row = array[rowIndex];
    for(int columnIndex = 0; columnIndex < row.length; columnIndex++) {
       int[] surroundingCells = getSurroundingCells(rowIndex, columnIndex);

此外,请注意,Java处理内存引用的方式是,设置一个变量的值只会改变该变量。您必须使用数组的索引设置语法来实际更改数组中给定点的值:
       int cell = array[rowIndex][columnIndex];
       cell = someValue; // This does nothing to your array values.
       array[rowIndex][columnIndex] = someValue; // This is what you want.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接