java - 通过引用传递double值 [英] java - passing a double value by reference
问题描述
如何在java中通过引用传递double值?
how can I pass a double value by reference in java?
示例:
Double a = 3.0;
Double b = a;
System.out.println("a: "+a+" b: "+b);
a = 5.0;
System.out.println("a: "+a+" b: "+b);
此代码打印:
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
我的目标:
我正在jess写一个专家系统,在那个应用程序中对于它的长度,segment将具有double值,现在double值不在单个段中;它存在于许多其他细分市场,比例类......等等,所有这些都引用它,等待它改变,以便它们可能符合一些规则。
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.
如果我不能得到那个双倍更改,我不能有一个特定的规则fire包含一个引用该double值的对象。
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不支持指针,所以你不能直接指向一个内存(如在C / C ++中)。
Java doesn't support pointers, so you can't point to a's memory directly (as in C / C++).
Java确实支持引用,但是引用只是对象的引用。无法引用本机(内置)类型。因此,当您执行时(自动装箱将您的代码转换为以下内容)。
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);
Double a = new Double(3.0);
这意味着当你执行时
Double b = a;
您获得了对象的引用。当您选择更改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);
这不会影响b对之前创建的 new Double(3.0)的引用)
。换句话说,你不能通过直接操作(或者在Java中没有远处的动作)来影响b的引用。
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
这篇关于java - 通过引用传递double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!