我有一个这样的数组:交换价值
item[0][0] = 1;
item[0][1] = 20;
item[1][0] = 3;
item[1][1] = 40;
item[2][0] = 9;
item[2][1] = 21;
(...)
我想交换这些“价值”,如:
int[] aux = item[0];
item[0] = item[1];
item[1] = aux;
但是,这是行不通的,因为我认为这是通过引用而不是值。
我有一个这样的数组:交换价值
item[0][0] = 1;
item[0][1] = 20;
item[1][0] = 3;
item[1][1] = 40;
item[2][0] = 9;
item[2][1] = 21;
(...)
我想交换这些“价值”,如:
int[] aux = item[0];
item[0] = item[1];
item[1] = aux;
但是,这是行不通的,因为我认为这是通过引用而不是值。
该问题与使用引用有关。
必须使用System.arraycopy(array, 0, otherArray, 0, array.length);
作为复制方法。
请问您可以发布多一点的代码,说明该解决方案如何解决您的问题? – SubOptimal
像这样?
public static void swapArrays(int a[], int b[]) {
if (a.length != b.length) {
throw new IllegalArgumentException("Arrays must be of same size");
}
int temp[] = Arrays.copyOf(a, a.length);
System.arraycopy(b, 0, a, 0, a.length);
System.arraycopy(temp, 0, b, 0, a.length);
}
public static void main(String[] args) {
int a[] = {1, 2, 3};
int b[] = {3, 4, 5};
swapArrays(a, b);
System.out.println(Arrays.toString(b));
}
如果它们的大小不同,则需要分配一个新数组或仅复制一定范围。
您的代码工作正常。见下文
int[][] item = {{1, 20}, {3, 40}, {9, 21}};
for (int[] ints : item) {
System.out.printf("%s ", Arrays.toString(ints));
}
System.out.println("");
// to swap the array item[0] and array item[1]
int[] aux = item[0];
item[0] = item[1];
item[1] = aux;
for (int[] ints : item) {
System.out.printf("%s ", Arrays.toString(ints));
}
System.out.println("");
输出的小片断
[1, 20] [3, 40] [9, 21]
[3, 40] [1, 20] [9, 21]
或一个阵列内交换的值(而不是交换两个阵列)
// to swap the values of array item[0]
// in the verbose way
int[] aux = item[0];
int temp = aux[0];
aux[0] = aux[1];
aux[1] = temp;
item[0] = aux;
for (int[] ints : item) {
System.out.printf("%s ", Arrays.toString(ints));
}
System.out.println("");
输出
[1, 20] [3, 40] [9, 21]
[20, 1] [3, 40] [9, 21]
@Kon,我正在处理一个多维数组...... – Christopher
你看到了什么错误?在代码中取得意想不到的结果? – Ryan
这应该工作。可能是别的东西不行?邮政输出你得到或任何错误。 – hitz