在群里有个同学发出如下问题,自己差点被绕进去,随后做出分析,还好.
让我困扰的主要原因是,我私以为java的赋值运算符是先运行右边,通过这次分析发现貌似并不是这样,而是先运行左边.
import java.util.Arrays;
public class TestMain {
public static void main(String[] args) {
int[] a = { 0, 0, 0, 0 };
int[] b = { 1, 2, 3, 4, 5 };
int[] c = a;
int i = 1;
a[++i] = (a = b)[i];
System.out.println("i=" + i);
System.out.println("a: " + Arrays.toString(a));
System.out.println("b: " + Arrays.toString(b));
System.out.println("c: " + Arrays.toString(c));
}
}
你认为上述代码结果会是怎样?
随后做出如下分析:
随后对代码做出修改证实:
import java.util.Arrays;
public class TestMain {
public static void main(String[] args) {
int[] a = { 0, 0, 0, 0 };
int[] b = { 1, 2, 3, 4, 5 };
int[] c = a;
int i = 1;
a[++i] = (a = b)[i];
a[0]=999;
b[1]=888;
System.out.println("i=" + i);
System.out.println("a: " + Arrays.toString(a));
System.out.println("b: " + Arrays.toString(b));
System.out.println("c: " + Arrays.toString(c));
}
}
运行结果: