2
class hello {
    public static void main(String arg[]){

    int[] c = { 2 };
    final int[] d = { 3 };

    }

static void useArgs(final int a, int b, final int[] c, int[] d) {

    c[0]=d[0]; // no error 
    c = d; //error 
    }
 }

伙计们,任何人都可以解释这种行为吗?

4

2 回答 2

6

变量c是最终的。这意味着您不能为该变量分配另一个值。

但是数组本身的元素不是最终的,这就是为什么您可以更改对元素的赋值,例如c[0]=d[0].

于 2013-03-10T06:44:09.757 回答
3

c 是对整数数组的最终(常量)引用。并且由于 c 是最终的,因此您无法更改其值(即更改它所指的地址)。这适用于任何声明为 final 的变量(不仅仅是数组)。

这也行不通:

final int c = 1;
int d = 2;
c = 2; // Error
c = d; // Error
于 2013-03-10T06:42:33.187 回答