Quoting some examples ...
1)
Integer i1 = 123;
Integer i2 = 123;
System.out.println(i1 == i2); //true
2)
Integer i1 = -129;
Integer i2 = -129;
System.out.println(i1 == i2); //false!!
The fact of the matter is that autoboxing is just an automatic wrapping & unwrapping of the primitives. == was never supposed to be used for comparing values. And autoboxing does not change those semantics (rightly).
P.S: While I'm talking about equality, here's how an IdentityHashMap differs from thae normal HashMap semantically (quoting from the docs)...
"in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)) .)"
(Remember, the contract b/w an hashCode() and equals() of an object requires that if you override the hashCode calculation, it is for you to handle the equality comparison as well, failing which, most HashMap implementations will bomb)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment