Increment a Integer's int value?
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);
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 int
s to Integer
s 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.
AtomicInteger
Maybe this is of some worth also: there is a Java class called AtomicInteger
.
This class has some useful methods like addAndGet(int delta)
or incrementAndGet()
(and their counterparts) which allow you to increment/decrement the value of the same instance. Though the class is designed to be used in the context of concurrency, it's also quite useful in other scenarios and probably fits your need.
final AtomicInteger count = new AtomicInteger( 0 ) ;
…
count.incrementAndGet(); // Ignoring the return value.