Integer- -
What’s hapen when writting using Java langage :
Integer myInt = new Integer(2);
myInt- -;
??
In fact, i had a Map and i was doing this on it :
Integer mynt = Map.get(myString);
myInt- -;
thinking that it would modified the map entry associated to myString.
I was wrong !!!!! Here the Java VM behaves the same way than writting :
myInt = new Integer(myInt.getValue() - 1);
What do you think about that ? To my eyes it’s quite confusing …
February 9, 2008 at 12:36 pm
Integer objects are immutable and cannot be modified.
Also, the code is really like this, after expanding:
Integer myInt = map.get(myString);
(myInt.intValue())–; //result discarded, because not assigned to a variable.
Actually the VM does not do what you describe, it executes the following, after autoboxing is used:
Integer myInt = map.get(myString);
int temp = myInt.intValue();
temp = temp - 1; //you never see temp, because it is never assigned to a vaiable in scope and is simply the int that the compiler unboxes the myInt object to.
It never changes the Integer object, because it is actually operating on the int returned by intValue().
Overall, the reason you can’t do what you want is that Integers are immutable.
You must create a new one, and put it in the map.
Integer myInt = map.get(myString);
myInt–; //unboxed, decremented, reboxed.
map.put(myString, myInt); //autoboxed if needed, and inserted into map.
This is standard java behaviour and is desirable, because it means ints can be passed around without needing to copy them. Any code can get the value out of the map and modify it, without worrying about altering the contents of the map.
February 9, 2008 at 12:39 pm
The code:
Integer myInt = new Integer(2);
myInt–;
Actually runs as:
Integer myInt = new Integer(2);
(myInt.intValue())–; //variable is lost, because you are not assigning result to anything. Original myInt is immutable.
February 13, 2008 at 7:14 am
Hi James,
The following code
Integer third = new Integer(3);
Integer oldThird = third;
System.out.println(oldThird == third);
third–;
System.out.println(oldThird == third);
prints this in stdout :
true
false
How can you explain this ??
Regards
May 27, 2008 at 7:11 am
Hola Manuel, llegue aquí por las notcias del uso de memoria de Eclipse
deberian marcarse de alguna forma, ya que su semántica es particular (aunque muy bien definida). En general, la gente no ha estado usando inmutables sino setX y tal … hasta que les convencieron de que un gen GC funciona bien.
Perdón, por la respuesta tardía (supongo que ya resolviste esto)
– es un “mutator” (x– equivale a x = x-1 “conceptualmente”), dado que third es inmutable third pasa a ser una nueva instancia … En Java, las clases (objetos) inmutables (”funcionales”
Es el mismo caso que cuando modificas un String (otro objeto funcional, “inmutable”), obtienes otro String distinto, no el mismo modificado.
May 27, 2008 at 7:16 am
Vaya wordpress se come uno de los - .