3

I'm doing the following comparison:

atividade.getEscala().getId() == escala.getId()

and it returns false but if I type atividade.getEscala().getId().intValue() == escala.getId().intValue() then it returns true. It also returns true when I write atividade.getEscala().getId().toString().equals(escala.getId().toString())

I know by debugging that the content of both variables is the same ( (java.lang.Long) 2 in display view ), then why does it returns false when I compare the longs with just ==?

StudioWorks
  • 483
  • 1
  • 6
  • 25

4 Answers4

12

When you use == with two references, you are comparing whether the references are the same, not whether the contents of the objects referenced are the same.

This is made more complicated with auto-boxing caches. e.g. Longs between -128 and 127 are cached so you will get the same object every time.

e.g.

Long x = 100, y = 100;
System.out.println(x == y); // true, references are the same.

Long a = 200, b = 200; // values not cached.
System.out.println(a == b); // false, references are not the same.
System.out.println(a.equals(b)); // true, the objects referenced are equal

Comparing the intValue() is dangerous due to the risk of overflow.

Long c = -1, d = Long.MAX_VALUE;
System.out.println(c.equals(d)); // false
System.out.println(c.longValue() == d.longValue()); // false
System.out.println(c.intValue() == d.intValue()); // true, lower 32-bits are the same.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

The == operator compares identity, not equality. For equality, use equals().

  • identity: Two distinct variables share a common object. In other words, they point to the same underlying object, and thus reference the same memory address.
  • equality: Two distinct objects represent the same thing. In other words, they are different objects, but have the same contents.
jweyrich
  • 31,198
  • 5
  • 66
  • 97
1

When you use == operator on objects you compare memory reference values, not values. For primitives you compare values.

alobodzk
  • 1,284
  • 2
  • 15
  • 27
1

If both values are Long, you need to compare them with equals(), as you do for all reference types. By calling intValue(), you're comparing int primatives, for which == works as you'd expect.

yshavit
  • 42,327
  • 7
  • 87
  • 124