h********m 发帖数: 116 | 1 static final变量的值不是不能改变的么?为啥我下面这个例子里面,数组a的值变了
呢?
public class testme {
static void change(int a[]){
a[0] = 5;
}
static final int a[] = {1, 2};
public static void main(String[] args) {
System.out.println("a = " + Arrays.toString(a));
change(a);
System.out.println("after change, a = " + Arrays.toString(a));
}
}
输出:
a = [1, 2]
after change, a = [5, 2] | p*****2 发帖数: 21240 | | d**e 发帖数: 6098 | 3 a本身的值应该是没变的,但这个值不是指它里面的值。
【在 h********m 的大作中提到】 : static final变量的值不是不能改变的么?为啥我下面这个例子里面,数组a的值变了 : 呢? : public class testme { : : static void change(int a[]){ : a[0] = 5; : } : static final int a[] = {1, 2}; : : public static void main(String[] args) {
| h********m 发帖数: 116 | 4 谢谢楼上两位的解释,看来我以前对final的理解有些误差。 | c********o 发帖数: 30 | 5 Final actually means that the reference can not change, not the content.
If you define
static final int[] a = [1, 2]; // let's say here a is pointing at address
0xffff,
int[] b ={5, 6} // here b is pointing at 0xCCCC
a = b; // this will give you error directly, as a cannot point to any other
address.
but a = {5, 6} is fine, as you can modify the content.
I just do some modification of your example, you use methods which contain
the int[] params:
import java.util.Arrays;
public class FinalExample {
static final int a[] = {1, 2};
static void change(int[] a){
a[0] = 5;
}
static void changeFinalArr(int[] a) {
int b[] = {5, 6};
a = b;
System.out.println("inside the method: a = " + Arrays.toString(a));
}
public static void main(String[] args) {
change(a);
System.out.println("a = " + Arrays.toString(a));
changeFinalArr(a);
System.out.println("try to change a's reference: a = " + Arrays.
toString(a));
}
}
Output:
a = [5, 2]
inside the method: a = [5, 6]
try to change a's reference: a = [5, 2]
If you use methods without params:
static void changeFinalArr() {
int b[] = {5, 6};
a = b; // this statement won't be able to compile as it has error
System.out.println("inside the method: a = " + Arrays.toString(a));
}
Sorry that I cannot type chinese in my office. :) |
|