Created
June 27, 2011 12:48
-
-
Save Keruspe/1048790 to your computer and use it in GitHub Desktop.
Why I do hate java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ | |
} | |
} |
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
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