【发布时间】:2021-03-23 20:20:10
【问题描述】:
我必须反转两个数组,以便它们具有相同的值但不同的引用。
这是我目前的代码。
但是当两个数组都指向同一个程序参数时,如何实现呢?
为什么String[] 引用反转String[] 值而不是反转程序参数?
例如。如果程序参数是1 2 3 4 5:
String[] values = 5 4 3 2 1
String[] reference = 1 2 3 4 5
public static void main(String[] args) {
String[] values = changeValues(args);
System.out.println(Arrays.toString(values));
String[] reference = changeReference(args);
System.out.println(Arrays.toString(reference));
if (!testSameValues(values, reference)) {
System.out.println("Error: Values do not match !");
}
if (testSameReference(values, reference)) {
System.out.println("Error: References are the same !");
}
}
public static String[] changeValues(String[] x) {
for (int i = 0; i < x.length / 2; i++) {
String temp = x[i];
x[i] = x[(x.length - 1) - i];
x[(x.length - 1) - i] = temp;
}
return x;
}
public static String[] changeReference(String[] y) {
for (int i = 0; i < y.length / 2; i++) {
String temp = y[i];
y[i] = y[(y.length - 1) - i];
y[(y.length - 1) - i] = temp;
}
return y;
}
public static boolean testSameValues(String[] x, String[] y) {
if (x.equals(y)) {
return true;
} else
return false;
}
public static boolean testSameReference(String[] x, String[] y) {
if (x == y) {
return true;
} else
return false;
}
【问题讨论】: