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?