How do I use an equivalent to C++ reference parameters in Java?

后端 未结 11 1272
借酒劲吻你
借酒劲吻你 2020-12-09 14:33

Suppose I have this in C++:

void test(int &i, int &j)
{
    ++i;
    ++j;
}

The values are altered inside the function and then use

相关标签:
11条回答
  • 2020-12-09 14:48

    The easiest solution is to use org.apache.commons.lang.mutable.MutableInt class you don't need to write by yourself.

    0 讨论(0)
  • 2020-12-09 14:50

    A better question: why are you creating methods with such side-effects?

    Generally, this is a strong indication that you should extract the data into a separate class, with public accessors that describe why the operation is taking place.

    0 讨论(0)
  • 2020-12-09 14:50

    Though its a bad design pattern IMHO, Another possible solution is

    static void test(AtomicInteger i, AtomicInteger j)
    {
        i.incrementAndGet();
        j.incrementAndGet();
    }
    
    0 讨论(0)
  • 2020-12-09 14:51

    Well, there are a couple of workarounds. You mentioned one yourself. Another one would be:

    public void test(int[] values) {
        ++values[0];
        ++values[1];
    }
    

    I would go with the custom object, though. It’s a much cleaner way. Also, try to re-arrange your problem so that a single method doesn’t need to return two values.

    0 讨论(0)
  • 2020-12-09 14:53

    You could construct boxed objects, ie,

    Integer iObj = new Integer(i);
    Integer jObj = new Integer(j);
    

    and write your routine as

    public void test(Integer i, Integer j){
      i = i.add(1);
      j = j.add(1);
    }
    

    For any number of reasons, the designers of Java felt call-by-value was better; they purposefully didn't include a method for call by reference. (Strictly, they pass copies of references to the objects, with the special case for the primitive types that they are purely call by value. But the effect is the same.)

    0 讨论(0)
  • 2020-12-09 14:55

    Java does not have pass-by-reference. You must encapsulate to achieve the desired functionality. Jon Skeet has a brief explanation why pass-by-reference was excluded from Java.

    0 讨论(0)
提交回复
热议问题