有关分配列表元素的错误


List<Integer> = New ArrayList<Integer>
//some other code,make sure that the size of list is bigger than 1
System.out.println(list.get(0).getClass().getName()); // print "System.lang.Integer"
list.get(0) = 1;   //this code does't work

为什么list.get(0) = 1IDE(eclipse)中给出以下错误?

赋值的左侧必须是变量。

list.get(0)的类型是Integer,不是吗? Integer test = 1;是正确的。

有人可以解释其中的区别吗?

不能将

方法调用的结果分配给数组访问表达式。 方法调用的结果list.get(0)是一个值,而不是一个变量。 这与数组访问表达式相反,例如 array[0] ,可以将其视为变量并位于表达式的左侧。

JLS 第 15.26 节通过在赋值运算符的左侧陈述唯一可以被视为"变量"的内容来支持这一点。

赋值运算符的第一个操作数的结果必须是变量,否则会发生编译时错误

此操作数可以是命名变量,例如局部变量或当前对象或类的字段,也可以是计算变量(如字段访问 (§15.11) 或数组访问 (§15.10.3) 的结果)。

请改用 set 方法。

list.set(0, 1);  // index, new value

list.get(0) 不是一个变量,而是一个常量。所以你需要使用 set() 或添加函数。

相关内容

最新更新