我试图理解为什么输出值在数组的情况下会改变,而在对象的情况下不会改变。
public class SameClass {
private Integer a;
private Integer b[];
public SameClass(Integer a) {
this.a=a;
}
public SameClass(Integer a, Integer b[]) {
this.a=a;
this.b=b;
}
public static void main(String args[]) {
Integer a = new Integer(5);
Integer b[] = {2,5};
// create two different objects
SameClass sam = new SameClass(a);
SameClass samB = new SameClass(a,b);
//change values in local variables
a=7;
b[0]= 8;
//print values
System.out.println(sam.a);
System.out.println(samB.b[0] + " " + samB.a);
}
}
这段代码的输出是:
5
8 5
最佳答案
//change values in local variables
a=7;
b[0]= 8;
您的评论是错误的:您没有更改局部变量b
中的值。您更改了 b
指向的数组中槽的值,并且从您的对象引用了同一数组。这就是为什么 a = 7
对您的对象没有影响,但 b[0] = 8
却有影响。
关于java - Java 中数组与非数组对象的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509909/