Hacker News new | ask | show | jobs
by chaosite 1016 days ago
That's a quirk of the language, sure, but it's barely an issue, and definitely not a worse issue. Don't get many wrong, Java has many issues, but this barely qualifies.

You don't compare non-primitives (which boxed integers are) with == in Java, you use the equals method.

2 comments

You definitely shouldn't compare them that way. But it still allows you to. That becomes a fairly big issue where you have the behavior working when you test it out and suddenly it doesn't work when the values become larger. Sure, an experienced Java developer will know this. How about a developer that is new to the language? Not as likely. I've personally lost over 6 hours to that one years and years ago.
CPython has the same thing, although with reverse syntax: you can use is to compare -5 to 256 rather than ==. I assume Java is also doing some caching of that int range for speed reasons.
What I really like in the space is what OCaml and Smalltalk do, where ints are full objects unto themselves with essentially a bit in the object header that says "interpret the rest of this object header as an int and if you need to do object style ops, you don't need a pointer to the class as the class is int", so there's no boxed versus unboxed int distinction in the first place. So primitive types versus class types exists at the VM level, but not the language level.

Obviously Java doesn't have the luxury of that decision at this point. But a lot of goofy parts of languages are string of fairly rational choices with unintended consequences.

You're not supposed to, but I've certainly found code out there that does use == to compare boxed integers because the test cases they used happen to work.

And in fact when I googled to find the exact range where it switches from cached integers to truly creating new objects, the top link was at best highly misleading. https://www.tutorialspoint.com/check-two-numbers-for-equalit...