Reputation:
I know that java does not support pass by reference. But still is there any possibility to implement it in any other ways if not directly as in C/C++?
Upvotes: 0
Views: 426
Reputation: 109547
Pass-by-value was by design: f(x)
will maybe alter the internals of the value of x, but x will not get another value. _For instance you cannot assign null to x inside f, using the formal parameter of f.
There is the possibility of in-out parameters which in java can be done by the function's result:
insertInNodes
is such a method.
public class SortedLinkedList<T extends Comparable<T>> {
private static class Node { ... }
Node head;
int size;
public void insert(T data) {
head = insertInNodes(head, data);
}
private Node insertInNodes(Node node, T data) {
if (node == null || data.compareTo(node.data) < 0) {
++size;
return new Node(data, node);
}
if (data.compareTo(node.data) > 0) {
node.next = insertInNodes(node.next, data);
}
return node;
}
}
Pass-by-reference needs to either fake it: pass a container object and then the component is actually a reference. For instance an array with one element or a wrapper class like Atomic<String>
.
Pass-by-reference in a more pure form could be realized by passing a getter and setter of the wanted "variable."
public void insert(T data) {
insertInNodes(this::getHead, this::setHead, data);
// Or insertInNodes(() -> head, (n) -> head = n, data);
}
private void insertInNodes(Supplier<Node> getter, Consumer<Node> setter, T data) {
if (getter.get() == null || data.compareTo(getter.get().data) < 0) {
++size;
setter.apply(new Node(data, getter.get()));
}
if (data.compareTo(node.data) > 0) {
// insertInNodes(() -> node.next, (n) -> node.next = n, data);
// or
insertInNodes(node::setNext, node::getNext, data);
}
return node;
}
Is this usable? No, only in specific use-cases.
Upvotes: 0
Reputation: 7273
If what you're trying to do is to have a "reference" to a primitive value which you can pass around, so you can modify the primitive's value inside methods and have the changes be visible outside said methods...
... just pass an array containing the primitive, like this:
// By value
int value = 1;
changeValue(value); // changes value to 5
System.out.println(value); // prints 1
// By "reference"
int[] reference = {1};
changeValue(reference); // changes value inside "reference" to 5
System.out.println(reference[0]); // prints 5
// Methods
void changeValue(int value) { value = 5; }
void changeValue(int[] reference) { reference[0] = 5; }
Bear in mind that this is not "pass by reference". Java is not passing a reference to the value, Java is passing the value of the array's reference.
You can read Is Java "pass-by-reference" or "pass-by-value"? for a better discussion about this.
Upvotes: 0
Reputation: 44150
Nope. You can't do it. It's not something you can "implement". It's a fundamental aspect of the language.
Upvotes: 3