Re: Updating an object in a HashMap
Matt Humphrey wrote:
<alacrite@gmail.com> wrote in message
news:09954880-5dd1-40f1-bae9-2c08f756059f@m34g2000hsb.googlegroups.com...
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?
The problem here is that Integers (along with Strings, Doubles, etc) are
immutable. For Integer i, the expression i += 5 is autoboxing shorthand for
i = new Integer (i.intValue() + 5)
<pedantry>
Actually, its short hand for i = Integer.valueOf(i.intValue()+5);
valueOf does some interning for a specific range of numbers.
</pedantry>
hm.get("test1") gives you the reference to Integer object, but is not itself
a variable that can be assigned to--it's just the returned expression value
(in this case the reference) Instead you must do
hm.put("test1", hm.get("test1") + 5)
Note that if you had an array of integers Integer [] iarray. you could say
iarray[j] += 5; because iarray[j] does work as a variable.
Matt Humphrey http://www.iviz.com/
Alternatively, you could do this:
public class IntWrapper {
private int value;
public void incBy(int inc) {
value += inc;
}
}
Map<String, IntWrapper> hm = getHm();
hm.get("test1").incBy(5);
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>