由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 问一个java的基本问题
相关主题
max sub vector sum 问题电话中写 code,不是给做弊的机会吗
问个外循环和内问题谁能猜猜,这是个什么 algorithm?
返回字符串所有的 combination【字符指针题】求帮助?
求教:贪心算法找零钱的精度问题?LRU question
问一个java的函数调用问题有好的merge有序数组算法么
请教一下subset I 输出子集顺序问题[算法]打印所有因子乘积组合
array 转换成 linkedlist, 在线等, 挺急的--help is still nee发一个有趣的java题
问一个static variable上锁的问题做了一道挺有意思的题
相关话题的讨论汇总
话题: static话题: change话题: int话题: void话题: final
进入JobHunting版参与讨论
1 (共1页)
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
2
a是final的,你并没有改变a。
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. :)
1 (共1页)
进入JobHunting版参与讨论
相关主题
做了一道挺有意思的题问一个java的函数调用问题
请问个算法复杂度请教一下subset I 输出子集顺序问题
一个多线程的题目,这个写法可以过关么array 转换成 linkedlist, 在线等, 挺急的--help is still nee
find Kth Largest Element 有没有更简化的解法问一个static variable上锁的问题
max sub vector sum 问题电话中写 code,不是给做弊的机会吗
问个外循环和内问题谁能猜猜,这是个什么 algorithm?
返回字符串所有的 combination【字符指针题】求帮助?
求教:贪心算法找零钱的精度问题?LRU question
相关话题的讨论汇总
话题: static话题: change话题: int话题: void话题: final