java - passing a double value by reference

后端 未结 6 2138
后悔当初
后悔当初 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:10

    The wrapper types are immutable in Java. Once they are created, their value cannot be changed (except via reflection magic ofcourse). Why are you trying to do what you're doing?

    Edit: Just to elaborate, when you set:

    a = 5.0;
    

    What actually ends up happening is something like:

    a = new Double(5.0);
    

    If double were mutable, you could have done something like

    a.setValue(5.0);// this would have worked for mutable objects, but not in this case
    

    You can of course write your own class, but there are a lot of pitfalls here, so it's best to explain you're goal

提交回复
热议问题