关于分配 List.element 的错误
error about assign List.element
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) = 1
在IDE(eclipse)
中报如下错误?
The left-hand side of an assignment must be a variable.
list.get(0)
的类型是 Integer
,不是吗? Integer test = 1;
正确。
有人可以解释一下区别吗?
不能将方法调用的结果当作数组访问表达式来赋值。方法调用的结果 list.get(0)
是一个值,而不是变量。这与数组访问表达式相反,例如array[0]
,可以当做变量,放在表达式的左边。
JLS, Section 15.26 通过在赋值运算符的左侧声明唯一可以被视为“变量”的内容来支持这一点。
The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs.
This operand may be a named variable, such as a local variable or a field of the current object or class, or it may be a computed variable, as can result from a field access (§15.11) or an array access (§15.10.3).
改为使用 the set
method。
list.set(0, 1); // index, new value
list.get(0) 不是变量而是常量。所以你需要使用set()或者add function.
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) = 1
在IDE(eclipse)
中报如下错误?
The left-hand side of an assignment must be a variable.
list.get(0)
的类型是 Integer
,不是吗? Integer test = 1;
正确。
有人可以解释一下区别吗?
不能将方法调用的结果当作数组访问表达式来赋值。方法调用的结果 list.get(0)
是一个值,而不是变量。这与数组访问表达式相反,例如array[0]
,可以当做变量,放在表达式的左边。
JLS, Section 15.26 通过在赋值运算符的左侧声明唯一可以被视为“变量”的内容来支持这一点。
The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs.
This operand may be a named variable, such as a local variable or a field of the current object or class, or it may be a computed variable, as can result from a field access (§15.11) or an array access (§15.10.3).
改为使用 the set
method。
list.set(0, 1); // index, new value
list.get(0) 不是变量而是常量。所以你需要使用set()或者add function.