[java] Increment a Integer's int value?

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);

This question is related to java class integer int

The answer is


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);

All the primitive wrapper objects are immutable.

I'm maybe late to the question but I want to add and clarify that when you do playerID++, what really happens is something like this:

playerID = Integer.valueOf( playerID.intValue() + 1);

Integer.valueOf(int) will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.


Java 7 and 8. Increment DOES change the reference, so it references to another Integer object. Look:

@Test
public void incInteger()
{
    Integer i = 5;
    Integer iOrig = i;
    ++i; // Same as i = i + 1;
    Assert.assertEquals(6, i.intValue());
    Assert.assertNotEquals(iOrig, i);
}

Integer by itself is still immutable.


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


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.


Maybe you can try:

final AtomicInteger i = new AtomicInteger(0);
i.set(1);
i.get();

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;

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. 

For Java 7, increment operator '++' works on Integers. Below is a tested example

    Integer i = new Integer( 12 );
    System.out.println(i); //12
    i = i++;
    System.out.println(i); //13

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift