Why wrapper class in Java doesn't behave like a reference type?

rybeusz :

I have a huge problem to understand why wrapper class in Java doesn't behave like a reference type. Example:

Integer one = 10;
Integer two = one;
one = 20;
System.out.println(one);
System.out.println(two);

The output will be:

20

10

I thought that two will be 20 like in this example where I create my own class:

class OwnInteger {
        private int integer;

        public OwnInteger(int integer) {
            this.integer = integer;
        }

        public int getInteger() {
            return integer;
        }

        public void setInteger(int integer) {
            this.integer = integer;
        }
    }

    OwnInteger one = new OwnInteger(10);
    OwnInteger two = one;
    one.setInteger(20);
    System.out.println(one.getInteger());
    System.out.println(two.getInteger());

So the question, is Integer wrapper class special? Why does it behave as I have shown in my examples?

dasblinkenlight :

This is exactly the behavior of a reference type. In your example, two references the same object as one after the assignment. However, re-assigning one a new object has no effect on two, which is the behavior that you see.

You will see the same behavior with other reference objects as well, for example

StringBuilder one = new StringBuilder("10");
StringBuilder two = one;
one = new StringBuilder("20");
// two still references StringBuilder with "10"

In order for a reference class to exhibit the behavior when changing one object also changes the other, the class needs to be mutable, like the OwnInteger class in your code, and the code needs to change the object, rather than reassigning it. Wrapper classes, such as Integer, are immutable, so you would not experience that behavior with them.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=472130&siteId=1