java - passing a double value by reference

后端 未结 6 2154
后悔当初
后悔当初 2021-01-04 13:58

how can I pass a double value by reference in java?

example:

Double a = 3.0;
Double b = a;
System.out.println(\"a: \"+a+\" b: \"+b);
a = 5.0;
System.         


        
6条回答
  •  太阳男子
    2021-01-04 14:21

    Double is immutable in Java. The assignment a = 5.0 is not changing the Double value of a. It is actually creating an entirely new Double object and changing the value of the pointer that a holds to point at that new object. If you want to be able to change the value without changing the reference, you need to make a mutable Double.

    public class MutableDouble {
      private Double value;
    
      public Double getValue() {
        return value;
      }
    
      public void setValue(Double value) {
        this.value = value;
      }
    
      @Override
      public String toString() {
        return value != null ? value.toString() : "null";
      }
    }
    

    Then you would call a.setValue(5.0); and both would change.

提交回复
热议问题