Reputation: 2173
From this book:
Find the kth to last element of a singly linked list. One of the proposed solutions is as follows:
public class IntWrapper{
public int value = 0;
}
Node nthToLast3(Node head, int k, IntWrapper i){
if (head == null){
return null;
}
Node node = nthToLast3(head.next, k, i);
i.value = i.value + 1;
if (i.value == k){
return head;
}
return node;
}
Why do we have to create the int Wrapper class and can't we use an int directly?
Upvotes: 0
Views: 228
Reputation: 476624
The point is that you want to be able to set the value of i
.
int
s are in Java implemented as primitive data, they are passed-by-value. This means that the following code doesn't set a
:
public void Foo () {
int a = 5;
System.out.println(a);//prints 5
setA(a);
System.out.println(a);//prints 5
}
public void setA (int a) {
a = 3;
}
Java copies the value of the variable on the stack and the copy is modified leaving the original a
untouched.
By using a Wrapper
, you store the int
in an object. Since object
s are passed-by-value from a "variable perspective", or passed-by-reference from the objects perspective, you refer to an object
that contains an int
. In other words, aw
referers to the same instance. Because you copied the reference an not the object. Changes made by the callee are thus reflected in the view of the caller.
public void Foo () {
IntWrapper aw = new IntWrapper();
aw.value = 5;
System.out.println(aw.value);//prints 5
setA(aw);
System.out.println(aw.value);//prints 3
}
public void setA (IntWrapper aw) {
aw.value = 3;
}
This is a useful hack in Java when you want to return multiple values or modify a variable of the caller.
C# alternatively provides the ref
keyword, that enable call-by-reference for primitive values.
Upvotes: -1
Reputation: 9071
The author uses IntWrapper
instead of an int
because he wants to achieve persistent state for a value between the callers and callees.
A modification to the int
member of an IntWrapper
instance in a callee will be visible to a caller.
With a plain int
, that's not possible because it's a primitive type, and hence it will be passed by value (it will be 'copied' if I may).
Upvotes: 2
Reputation: 6005
What this trick does, is to wrap an int
(native type) in an object (Object
derived type). Everything is passed by value in Java
, and for objects, the value of the reference is passed as an argument, in a sense (think of it like a pointer value in C/C++
, for example).
Upvotes: 3
Reputation: 4549
It is impossible in Java to pass primitive values by reference. This is a restriction on the language itself.
Technically, the only things you can pass into methods are "primitives, and pointers to objects". The latter also being a form of primitive. Java possesses neither references nor const object passing.
Upvotes: 2