Skip to content

Instantly share code, notes, and snippets.

@Keruspe
Created June 27, 2011 12:48
Show Gist options
  • Save Keruspe/1048790 to your computer and use it in GitHub Desktop.
Save Keruspe/1048790 to your computer and use it in GitHub Desktop.
Why I do hate java
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
*/
}
}
@judu
Copy link

judu commented Jun 27, 2011

public void inc2(Integer i) {
try {
f = i.getClass().getDeclaredField("value");
f.setAccessible(true);
f.set(i, i+1);
} catch (NoSuchFieldException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}

@Keruspe
Copy link
Author

Keruspe commented Jun 27, 2011

loljava

@kepstin
Copy link

kepstin commented Jun 27, 2011

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.

@Keruspe
Copy link
Author

Keruspe commented Jun 27, 2011

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

@kepstin
Copy link

kepstin commented Jun 27, 2011

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 ☺

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment