java - 链式数组值

标签 java arrays methods

我创建了一种名为 rowSwitching 的方法来切换数组中两个特定行上的数据。然而,当我使用它时,即使我不想存储它,主要的数组值也发生了变化。

这是我的代码;

public class MatrixEx {//implements Matrix {

public static void print(int[][] input1, int[][] input2) {
    System.out.println("------------------ ------------------");
    for (int row = 0; row < input1.length; row++) {
        for (int col = 0; col < input1.length; col++) {
            System.out.format("%4d", input1[row][col]);
        }
        System.out.print("          ");
        for (int col = 0; col < input2.length; col++) {
            System.out.format("%4d", input2[row][col]);
        }
        System.out.println();
    }
    System.out.println("------------------ ------------------");
}

public static void main(String[] args) {

    int[][] input1 = {
        {7, 2, 1},
        {0, 3, -1},
        {-3, 4, -2}
    };

    int[][] input2 = {
        {-2, 8, -5},
        {3, -11, 7},
        {9, -34, 21}
    };

    System.out.format("%12s%4s%12s\n", "input1", " ", "input2");
    print(input1, input2);

    MatrixEx matrixFunc = new MatrixEx();
    print(input1, matrixFunc.rowSwitching(input1, 1, 2));

}

public int[][] rowSwitching(int[][] matrix, int row1, int row2) {
    System.out.format("%12s%4s%12s\n", "Before", " ", "After");
    int[] temp1 = new int[matrix.length];
    int[] temp2 = new int[matrix.length];
    int[][] result = matrix;

    row1 -= 1;
    row2 -= 1;

    for (int i = 0; i < temp1.length; i++) {
        temp1[i] = result[row1][i];
    }

    for (int i = 0; i < temp2.length; i++) {
        temp2[i] = result[row2][i];
    }

    for (int i = 0; i < result.length; i++) {
        result[row1][i] = temp2[i];
    }

    for (int i = 0; i < result.length; i++) {
        result[row2][i] = temp1[i];
    }        
    return result;
}

我想将数组值保留在 main 中,但由于某种原因它在我使用该方法后不断变化。

最佳答案

在 Java 中,任何对象类型(包括数组)都是通过引用传递的。这意味着如果你有一个函数

private void doThings(int[] items) {
  items[0] = 10;
}

你称之为:

int[] myList = new int[3] {1,2,3};
doThings(myList);
System.out.println(myList[0]); // Prints '10'

这是因为 doThings 接收到列表在内存中存储位置的引用,并更改存储它的实际内存 - 也在 main 中更改它。

您可能需要重新考虑您的程序或 copy the array

关于java - 链式数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728622/

相关文章:

javascript - 你在 catch 语句中对 JAvascript err 调用什么方法

javascript - 在 HTML URL 中使用数组

Javascript 数组和 JQuery .param

java - 在 Java 中调用多个方法

java - 删除 bitbuck 中的文件夹

arrays - Postgres 用值数组替换函数

ruby - 为什么 Method#arity 被称为 arity?

java - 线程安全、静态方法和一些奇怪的代码

java - 在 Ubuntu Lucid linux 中设置 Java

java - 如何使用 javascript/jquery 获取 html struts styleClass