Hacker News new | past | comments | ask | show | jobs | submit login

Argh, the complexities of Java!

Integer a = new Integer(10);

Integer b = new Integer(10);

Integer c = new Integer(1000);

Integer d = new Integer(1000);

a==b is true

c==d is false




Sorry to break it out to you but you picked a bad example; the equivalent Python code has the same WTF effect:

Python 2.6.6 (r266:84292, Oct 17 2010, 15:53:05)

[GCC 4.4.3] on linux2

>>> a = int(10)

>>> b = int(10)

>>> c = int(1000)

>>> d = int(1000)

>>> a is b

True

>>> c is d

False


Wow! Really? (I'm not a Pythonator.)

Same reasoning as Java?


Basically yes, although it is not part of the language definition and should not be relied on. It's just an implementation artifact of CPython, and not only that but the threshold of which integers are cached changes for different Python versions.


It's simple, right? The result of <Integer> == <Integer> is undefined with respect to the value that is stored in the Integer object.


A bit more subtle than that- Java reserves singleton instances of Integer for values in the range -128 to 127. In these cases, the Integers will contain the same value and refer to the same object, so == works. It's not actually undefined behavior.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: