Passing by reference in Java?

后端 未结 4 1365
Happy的楠姐
Happy的楠姐 2020-12-20 22:19

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 are primitive types such as int.

4条回答
  •  时光取名叫无心
    2020-12-20 22:56

    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.

提交回复
热议问题