开发者

Passing by reference in Java?

开发者 https://www.devze.com 2022-12-24 22:56 出处:网络
In C++, if you need to have 2 objects modified, you can pass by reference. How do you accomplish this in java? Assume the 2 objects ar开发者_运维技巧e primitive types such as int. You can\'t. Java doe

In C++, if you need to have 2 objects modified, you can pass by reference. How do you accomplish this in java? Assume the 2 objects ar开发者_运维技巧e primitive types such as int.


You can't. Java doesn't support passing references to variables. Everything is passed by value.

Of course, when a reference to an object is passed by value, it'll point to the same object, but this is not calling by reference.


Wrap them in an object and then pass that object as a parameter to the method.

For example, the following C++ code:

bool divmod(double a, double b, double & dividend, double & remainder) {
  if(b == 0) return false;
  dividend = a / b;
  remainder = a % b;
  return true;
}

can be rewritten in Java as:

class DivRem {
  double dividend;
  double remainder;
}

boolean divmod(double a, double b, DivRem c) {
  if(b == 0) return false;
  c.dividend = a / b;
  c.remainder = a % b;
  return true;
}

Although more idiomatic style in Java would be to create and return this object from the method instead of accepting it as a parameter:

class DivRem {
  double dividend;
  double remainder;
}

DivRem divmod(double a, double b) {
  if(b == 0) throw new ArithmeticException("Divide by zero");
  DivRem c = new DivRem();
  c.dividend = a / b;
  c.remainder = a % b;
  return c;
}


Java does not have pass by reference, but you can still mutate objects from those references (which themselves are passed by value).

  • java.util.Arrays.fill(int[] arr, int val) -- fills an int array with a given int value
  • java.util.Collections.swap(List<?> list, int i, int j) -- swaps two elements of a list
  • StringBuilder.ensureCapacity(int min) -- self-explanatory

As you can see, you can still modify objects (if they're not immutable); you just can't modify references or primitives by passing them to a function.

Of course, you can make them fields of an object and pass those objects around and set them to whatever you wish. But that is still not pass by reference.


Using generics you can create a pointer class which would make this at least somewhat less painful. You pass in the object, change it's value property and when the function exits your object will contain the new value.

MyPointerClass<int> PointerClass = new MyPointerClass<int>(5);
myFunction(PointerClass);
System.out.println(PointerClass.Value.toString());

// ...

void myFunction(myPointerClass<int> SomeValue)
{
  SomeValue.Value = 10;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号