Search code examples
javaintegermutability

Manipulating an Integer Object Without creating a new Instance?


I have:

// lets call this Integer reference ABC101
Integer i = new Integer(5);

//j points to i so j has the reference ABC101
Integer j = i;

//creates a new Integer instance for j?
j++;
//I want j++ to edit and return ABC101
System.out.println(i); // 5 not 6

So my goal is to manipulate I via a different Object with the same reference without switching references. And no don't say, "Why don't you just use ints or why don't you just mess with I directly". That isn't the purpose of this exercise. There is always easier ways to do things, but this is what I'm supposed to be dealing with. Last question... does that mean Integer objects are immutable?


Solution

  • Indeed, all primitives (int, boolean, double etc.) and their respective Wrapper classes are immutable.

    It is not possible to use the postincrement operator j++ to change the value of i. This is because j++ translates to j = j + 1 and the assignment operator = means that i and j no longer refer to the same object.

    What you could do is either use an array of int (or Integer, whatever you prefer). Your code would then look like this

    int i[] = {5};
    
    int j[] = i;
    
    j[0]++;
    System.out.println(i[0]); // prints 6
    

    This is however not recommended. In my opinion you should use your own wrappe class for int that could look like this

    public class MutableInt
    
    private int i;
    public MutableInt(int i) {
      set(i);
    }
    
    public int get() {
      return i;
    }
    
    public void set(int i) {
      this.i = i;
    }
    
    public void increment() {
      i++;
    }
    
    // more stuff if you want to
    

    Be aware that you won't be able to use autoboxing this way and that there is no Cache like for java.lang.Integer