-
-
Save Keruspe/1048790 to your computer and use it in GitHub Desktop.
public class Ref { | |
public void inc1(int i) { | |
++i; | |
} | |
public void inc2(Integer i) { | |
++i; | |
} | |
public static void main(String[] args) { | |
int foo = 32; | |
Integer bar = 41; | |
Ref r = new Ref(); | |
System.out.println("Expected: 32x41\nGot: " + foo + "x" + bar); | |
r.inc1(foo); | |
System.out.println("Expected: 32x41\nGot: " + foo + "x" + bar); | |
r.inc2(bar); | |
System.out.println("Expected: 32x42\nGot: " + foo + "x" + bar); | |
r.inc1(bar); | |
System.out.println("Expected: 32x42\nGot: " + foo + "x" + bar); | |
r.inc2(foo); | |
System.out.println("Expected: 32x42\nGot: " + foo + "x" + bar); | |
/* Output: | |
Expected: 32x41 | |
Got: 32x41 | |
Expected: 32x41 | |
Got: 32x41 | |
Expected: 32x42 | |
Got: 32x41 | |
Expected: 32x42 | |
Got: 32x41 | |
Expected: 32x42 | |
Got: 32x41 | |
*/ | |
} | |
} |
Yep, I totally agree, but that is actually my point, when passing an Integer to a method which takes as parameter an Integer, a reference is passed, but changing the value of the Integer with the ++ operator creates a new Integer and thus does not modify the Integer it was given. That kinda sucks not to be able to do such a thing without using the reflection API ...
In this case there is no big deal, I can return i; at the end, but if I want a method with two in-out Integers, I'm stuck and have to make them fields of a class which I will pass, and that's not handy at all. I really prefer the vala or C way for exemple, for this kind of stuff
Oh, I see… I wasn’t quite paying enough attention. Yes, it is odd how Integer is an effectively immutable object like that, which is different from most other Java objects.
I’m not a particularly big fan of Java myself, or I might have noticed that sooner ☺
This makes perfect sense, really… “int” is a basic type, and is therefore passed by value. “Integer” is an object (basically an object wrapper around an int), and is therefore passed by reference, like any other Java object.