Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shallow copy Integer in Java

Tags:

java

variables

Other answers don't work for me. My question is about Integer.

Integer i1 = new Integer(11);
Integer i2 ;
i2 = i1;
System.out.println(i1+"   "+i2);
i1 = 233;
System.out.println(i1+"   "+i2);
//~ 11    11
//~ 233    11

I want to let i1 and i2 related.

like image 699
张泽栋 Avatar asked Dec 14 '22 03:12

张泽栋


1 Answers

In java java.lang.Integer is immutable. It means that you can't change the value of Integer object (in usual way). You can create new Integer instance with new value.

i1 and i2 contains a reference to the same Integer instance. When you made

i1 = 233;

it means that i1 refers to another instance of Integer class

If you want that i1 and i2 refers to the same instance you can use AtomicInteger, but AtomicInteger was made for different purpose.

AtomicInteger i1 = new AtomicInteger(11);
AtomicInteger i2 ;
i2 = i1;
System.out.println(i1+"   "+i2);
i1.set(233);
System.out.println(i1+"   "+i2);

Or you can make a wrapper

public static class IntegerWrapper {

    private int value;

    public IntegerWrapper(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public IntegerWrapper setValue(int value) {
        this.value = value;
        return this;
    }
}

and code

IntegerWrapper i1 = new IntegerWrapper(11);
IntegerWrapper i2 ;
i2 = i1;
System.out.println(i1.getValue()+"   "+i2.getValue());
i1.setValue(233);
System.out.println(i1.getValue()+"   "+i2.getValue());
like image 163
Vadeg Avatar answered Dec 25 '22 20:12

Vadeg