java double地址传递,java - 通过引用传递double值

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.out.println("a: "+a+" b: "+b);

this code prints:

a: 3 b: 3

a: 5 b: 3

and my problem is to get it to print:

a: 3 b: 3

a: 5 b: 5

my goal:

I'm writing an expert system in jess, in that application a segment would have a double value for it's length, now that double value isn't in a single segment; it's in many other segments, proportionality classes..etc, all of which are referencing to it, waiting it to change so that they could possibly meet some rules.

if I can't get that double to change, I can't have a certain rule fire which contains an object that references to that double value.

解决方案

Java doesn't support pointers, so you can't point to a's memory directly (as in C / C++).

Java does support references, but references are only references to Objects. Native (built-in) types cannot be referenced. So when you executed (autoboxing converted the code for you to the following).

Double a = new Double(3.0);

That means that when you execute

Double b = a;

you gain a reference to a's Object. When you opt to change a (autoboxing will eventually convert your code above to this)

a = new Double(5.0);

Which won't impact b's reference to the previously created new Double(3.0). In other words, you can't impact b's reference by manipulating a directly (or there's no "action at a distance" in Java).

That said, there are other solutions

public class MutableDouble() {

private double value;

public MutableDouble(double value) {

this.value = value;

}

public double getValue() {

return this.value;

}

public void setValue(double value) {

this.value = value;

}

}

MutableDouble a = new MutableDouble(3.0);

MutableDouble b = a;

a.setValue(5.0);

b.getValue(); // equals 5.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值