views:

96

answers:

4

How do I increment a Integer's value in Java? I know I can get the value with intValue, and I can set it with new Integer(int i).

playerID.intValue()++;

does not seem to work.

Note: PlayerID is a Integer that has been created with:

Integer playerID = new Integer(1);
+4  A: 

Integer objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer and replace the existing one.

playerID = new Integer(playerID.intValue() + 1);
Grodriguez
If you must use a non-primitive int, and you want mutability, you can try commons MutableInt http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/mutable/MutableInt.html
Joel
thanks, but for some reason it's still not incrementing. Maybe it's a bug in my code...
William
@William : As i know, it will be incremented only in method that increment it.
Stas
Don't use Integer's constructor.
ColinD
Here we are) http://stackoverflow.com/questions/3815273/integer-wont-increment/
Stas
@ColinD: I believe that spelling it out like this makes it easier to see what is actually going on.
Grodriguez
@Grodriguez: Perhaps, though even then I'd suggest `Integer.valueOf(int)`... I don't like the idea of using bad practices in answers at all, it can lead to people thinking they're ok to do. I also think it's useful for the OP to realize that he can use operations he'd use with an `int` with an `Integer` in the same manner.
ColinD
@ColinD: "can lead to people thinking they're ok to do so"? I'm sorry, but it **is** OK to use the constructor, even though `Integer.valueOf(int)` is better. The fact that there are better alternatives (where available -- please note that some people is still stuck on pre-1.5 environments for different reasons) does not mean that using the constructor is "bad practice". And I still believe that my answer was clearer the way I wrote it.
Grodriguez
A: 

Integer objects are immutable. You can't change the value of the integer held by the object itself, but you can just create a new Integer object to hold the result:

Integer start = new Integer(5);
Integer end = start + 5; // end == 10;
RHSeeger
A: 

You can use IntHolder as mutable alternative to Integer. But does it worth?

Stas
+2  A: 

As Grodriguez says, Integer objects are immutable. The problem here is that you're trying to increment the int value of the player ID rather than the ID itself. In Java 5+, you can just write playerID++.

As a side note, never ever call Integer's constructor. Take advantage of autoboxing by just assigning ints to Integers directly, like Integer foo = 5. This will use Integer.valueOf(int) transparently, which is superior to the constructor because it doesn't always have to create a new object.

ColinD