Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That's common. Same for the one-character strings.

That's a sticking point with a lot of young Java programmers encountering boxed types for the first time. They see that x is true here:

  Integer x = new Integer(5);
  Integer y = new Integer(5);
  x == y
But this is false:

  Integer x = new Integer(5000);
  Integer y = new Integer(5000);
  x == y
(The real fix, of course, is to use the 'equals' method when comparing objects.)


I'd argue the real fix is to use a language that doesn't have insane semantics for ==.


No, Java's semantics for == are entirely sane and straightforward: It compares primitives by value, and objects by identity in memory.

The true problem is that newbies who haven't grasped the difference see that x==y in a sample program and then leap to all sorts of conclusions, overgeneralizing what they observed because they don't understand how it happened.


The problem is that comparing by value is not a good default for ==. A language should strive to make the common tasks as simple as possible to do right, while not making it impossible to check object equality or some other kind of equality.

Compare Ruby:

  1 == 1 => true
  4711 == 4711 => true

  1.object_id == 1.object_id => true
  4711.object_id == 4711.object_id => false


The #equal? method does your object_id comparison, by the way.

Ruby's default #== for new classes simply performs identity comparison, just like in Java. The difference is that Ruby has operator overloading, so all the builtin classes overload it with something sensible.

(This could work in Java, or it could go the .NET route and ban using the == operator entirely until a certain interface (.NET's IEquatable) is fulfilled.)




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

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

Search: