Someone must be hit really hard with some curly braces when he implemented the following behaviour:
public class Braindead { public static void main(String[] args) { Integer i1 = 10; Integer i2 = 10; Integer i3 = 128; Integer i4 = 128; compare(i1, i2); compare(20, 20); compare(i3, i4); } public static void compare(Integer i1, Integer i2) { System.out.println("Comparing " + i1 + " and " + i2); if(i1 == i2) System.out.print("same "); else System.out.print("different "); System.out.println("Objects"); if(!i1.equals(i2)) System.out.print("not "); System.out.println("meaningfully equal"); System.out.println("---"); } } |
I’d expect the following output:
Comparing 10 and 10 different Objects meaningfully equal --- Comparing 20 and 20 different Objects meaningfully equal --- Comparing 128 and 128 different Objects meaningfully equal ---
What you get is:
Comparing 10 and 10 same Objects meaningfully equal --- Comparing 20 and 20 same Objects meaningfully equal --- Comparing 128 and 128 different Objects meaningfully equal ---
In order to save memory, two instances of the following wrapper objects will always be == when their primitive values are the same:
- Boolean
- Byte
- Character from \u0000 to \u007f
- Short and Integer from -128 to 127
So in order to save a handfull of bytes we present you some really inconvenient feature 😉
2 comments
Well, just another example showing how half-assed OO is in Java 😉
Hark hark…
I tell you, i fell deep into “love” with ruby…
The most annoying j2ee thing is the mess of all those damn xml configuration files…
Post a Comment