Hacker News new | ask | show | jobs
by kyrra 4398 days ago
It also leads to some interesting programming errors in Java.

    class A {
        public static void main(String[] args) {
            Integer a = 100, b = 100;
            Integer c = 10000, d = 10000;
            System.out.println(a == b);
            System.out.println(c == d);
        }
    }
Prints:

    true
    false
For those unaware, the == check above is doing an Object check (are they the same object). The cache makes the '100' return the same instance of an object. To do actual value checks, you'd need to do c.equals(d)
1 comments

what a dumb language! operator overloading should have bound the equals method to the == operator without the programmer having to be aware of this. when in java do you ever want to compare if two objects are the same referenced with the same ptr? Never, so why not do the right thing by the user of the language.

At least be consistent between primitives and objectives.

Sadly, I have to use this language daily. My heart belongs to python, but java pays the bills.

You're forgetting legacy and history. Many Java programmers came to Java, myself included, from C (or C++). The == operator in C is a simple register comparison. If you compare two ints the the == operator will return true iff the two int values are the same, but if you compare two int pointers, then equal integer values may or may not be stored at the same address, which is exactly what we're seeing here. Since Java references are pointers, this behavior -- while probably not the right choice -- was less surprising to us, C programmers, than the alternative. Of course, auto-boxing made this behavior even stranger, but autoboxing was added to the language much later.
Python has exactly the same behavior if you compare integers using the is operator. Two int-variables with same value are only "is-equal" up until somewhere around 100000 also. Many beginners do this mistake as they think you should always use is in python and don't even know that == also exist.