Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - passing a double value by reference

Tags:

java

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.

like image 896
Ouais Avatar asked Apr 21 '11 20:04

Ouais


1 Answers

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
like image 124
Edwin Buck Avatar answered Oct 24 '22 06:10

Edwin Buck