Re: Updating an object in a HashMap
On 2008-02-14 04:36 +0100, alacrite@gmail.com allegedly wrote:
On Feb 13, 6:00 pm, alacr...@gmail.com wrote:
import java.util.HashMap;
import java.lang.System;;
public class HashMapTest
{
public static void main(String args[])
{
HashMap<String,Integer> hm = new HashMap<String,Integer>();
hm.put("test1",0);
hm.get("test1").intValue() += 5;
//Error:The left-hand side of an assignment must be a variable
System.out.println(hm.get("test1"));
}
}
I want to update a Value in a HashMap. I know the Key. I would have
assumed the above code would work. Instead, I am given an error, "The
left-hand side of an assignment must be a variable".
Does this mean that the value returned is the literal value? In this
case 0. I would have assume a reference to the object would have been
returned and calling += would have unboxed the Integer and aggregated
the value.
Could someone explain to me what is going on? Also, what is the best
way to accomplish updating this value?
Thanks.
Thank you all for your replies. I did not realize that Boolean, Byte,
Short, Character, Long,
Float, and Double objects were immutable.
This has NOTHING to do with immutable or not.
Two replies have stated this. Though their work-around was correct,
their reason was plain wrong.
It has NOTHING to do with immutability. It has to do with what's a valid
statement and what's not, more precisely what's a valid assignment
statement and what's not.
See:
<http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5281>
It defines the LeftHandSide (LHS) and states accordingly:
"The result of the first operand [<=> LHS] 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.13)"
That is why. <rant>As your compiler clearly told you.</rant>
@Lew: the page just referred to mentions lvalues, which I too had until
now thought common terminology in Java, on the top of the page. That's
one of only two results a google search with
"site:http://java.sun.com/docs/books/jls/third_edition/html/expressions.html"
yielded.
DF.