0

In the application, I needed to create a copy of an object that contained Double and Integer fields. It turned out that the calls: doubleValue() methods for Integer instances, and intValue() methods for Double instances behave differently, which surprised me. Here is an example:

class TestClass {
    private Integer intVal;
    private Double doubleVal;

    public Integer getIntVal() {
        return intVal;
    }

    public void setIntVal(Integer intVal) {
        this.intVal = intVal;
    }

    public Double getDoubleVal() {
       return doubleVal;
    }

    public void setDoubleVal(Double doubleVal) {
        this.doubleVal = doubleVal;
    }
}

private void testInteger() {
    TestClass inst1 = new TestClass();
    inst1.setDoubleVal( 20.0 );
    inst1.setIntVal( 10 );
    TestClass inst2 = new TestClass();
    inst2.setDoubleVal( inst1.getDoubleVal().doubleValue() );
    inst2.setIntVal( inst1.getIntVal().intValue() );
}

When

inst2.setDoubleVal( inst1.getDoubleVal().doubleValue() );

was called, the inst2.doubleVal property was a different object than ins1.doubleVal.

When

inst2.setIntVal( inst1.getIntVal().intValue() );

was called, inst2.intVal was the same object as ins1.instVal.

Here is the information from the debugger:

inst1.doubleVal = {Double@7183} 20.0 inst2.doubleVal = {Double@7187} 20.0 inst1.intVal = {Integer@7184} 10 inst2.intVal = (Integer@7184} 10

Could someone please explain this to me?

Wiatrak
  • 21
  • 3
  • `Integer` has a cache (by default I think it covers `-128` to `127` or something like that). – Slaw Oct 05 '21 at 19:36
  • Ach... Now understand... Thank you very much. I skipped this problem using new Integer(): inst2.setIntVal( new Integer(inst1.getIntVal().intValue()) ); – Wiatrak Oct 05 '21 at 19:40
  • 2
    "I skipped this problem using ...": why do you think it is a problem that both `TestClass` instances reference the same `Integer` object? – Thomas Kläger Oct 05 '21 at 20:08
  • Thomas, at first, I wanted to answer you: because if I change the value of Integer in inst1, in inst2 value will be changed too. But you just made me realize that this is not true, because Integer objects are immutable! Thank you very much! :-) – Wiatrak Oct 06 '21 at 20:11

0 Answers0