Using pointers in Java

From: S Manohar (sgmanohar_at_hotmail.com)
Date: 01/30/04

  • Next message: hiwa: "Re: [Q] How to save a Map, which has non-primitive data, in a file"
    Date: 30 Jan 2004 14:05:44 -0800
    
    

    I need to pass a 'reference' to a double value to a function which
    changes that value. Each time the function is called, it needs to
    change different sets of values. In C I'd simply pass references.

    void add(double *a1, double *a2, double *a3){
     *a1 = *a2 + *a3;
     *a2 = *a1 + *a3;
    }

    In Java, one solution would be to create a class to represent a
    mutable value:

    public class MutableDouble {
     private double value;
     public final void set(double value){ this.value=value; }
     public final double get(){ return value; }
    }

    But, my this is cumbersome in my code for several reasons:

    1) My code contains many long mathematical equations, which become
    very convoluted using this syntax, with ridiculous numbers of
    parentheses! It is very important that the maths in the code is
    readable, as someone else may have to work on my code. E.g.,
     a = a + 1
    becomes
     a.set(a.get()+1)
    The problem is, of course, that unlike C++, operators cannot be
    defined.

    2) get() and set() will presumably be slower than direct use of
    values. Though I don't know enough about how the javac inlines
    functions.

    3) I need to define a MutableInteger, MutableLong and MutableFloat as
    well.

    4) The size of the compiled code will be, presumably, more bulky.

    So, This is the kind of solution I am thinking of adopting:

    void test(){
     double[] x=new double[1], y=new double[1];
     add(x,y,y);
    }

    void add(double[] a1, double[] a2, double[] a3){
     a1[0] = a2[0] + a3[0];
     a2[0] = a1[0] + a3[0];
    }

    Using arrays of length 1 as pointers has some advantages, seems
    'cheap' in terms of code and memory, and the code will look much nicer
    than using get/set. But naturally there are disadvantages, e.g., as
    with pointers, there's the potential for inadvertent null-pointer
    exceptions (which will be ArrayIndexOutOfBounds exceptions).

    Has anyone used this method?

    Has anyone any comments on its effectiveness and/or problems?

    What is your opinion on its methodological purity?

    Sanjay


  • Next message: hiwa: "Re: [Q] How to save a Map, which has non-primitive data, in a file"