简体   繁体   English

在JAVA中通过ref,double和Double传递参数

[英]Passing parametars by ref, double and Double in JAVA

If someone could help me understand the following problem: 如果有人可以帮助我了解以下问题:

As I understand double is primitive data type in Java and Double is immutable class. 据我了解, double是Java中的原始数据类型,而Double是不可变的类。 Every parameter is passed by value. 每个参数都按值传递。 If it is primitive type ( int , double , byte ), then it is the actual value that is passed; 如果它是原始类型( intdoublebyte ),则它是传递的实际值; and if it is an object type, then it is the address to that object that is copied. 如果是对象类型,则复制对象的地址。

If that is so, why this parameter that is of type Double is not changed? 如果是这样,为什么不更改Double类型的此参数?

...
    public static void main(String[] args) {
        Double value = new Double(0);

        SomeObj so = new SomeObj();
        so.setNewValue(value);

        System.out.println(value);
    }
...

public class SomeObj {
    public void setNewValue(Double changeMe)
    {
        changeMe = new Double(10.0);
    }
}

It is the reference to the object that is passed by value . 它是对按值传递的对象的引用 In the setNewValue method, you change the reference, so the changeMe variable points to something else. setNewValue方法中,您可以更改引用,因此changeMe变量指向其他对象。 The (reference to the) original value object in the main method is not changed. main方法中的(对原始value对象的引用)不变。

see also Is Java "pass-by-reference" or "pass-by-value"? 另请参见Java是“按引用传递”还是“按值传递”?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM