• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals or identity

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I compare two Short values a and b, then I need to compare it via:



or via



this:

I have found out, that this a.equals(b); is strangely not the same as this a.equals((short) b);

Should I compare wrapper classes (Integer, Long, Short) via equals or via '==' ? In primitive types, we compare via '=='.

(I know the difference of equals and identity)
 
Rob Spoor
Sheriff
Pie
Posts: 20665
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nimo frey wrote:Should I compare wrapper classes (Integer, Long, Short) via equals or via '==' ?

Via equals.

== only works for values between -128 and 127 (inclusive) for Byte, Short, Integer and Long, and for values between 0 and 127 for Character. And only if the object was retrieved using the static valueOf(primitive) method. Otherwise, a new object is created and == will return false.
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nimo frey wrote:
I have found out, that this a.equals(b); is strangely not the same as this a.equals((short) b);


I don't understand why these should return different values. The Short wrapper class has just one overridden equals() method so both of these should give the same result.

Can you provide a code snippet where you end up getting different values for the two?
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay thank you!
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand why these should return different values. The Short wrapper class has just one overridden equals() method so both of these should give the same result.


I do not understand, either.

Look at this:



So I have to explicitly cast my 0-value to short. Very cumbersome.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nimo frey wrote:
I don't understand why these should return different values. The Short wrapper class has just one overridden equals() method so both of these should give the same result.


I do not understand, either.

Look at this:



So I have to explicitly cast my 0-value to short. Very cumbersome.


That is not what you described in your first post. You said you had two Short values.

Here you have a Short and an int literal (0). The int will be autoboxed into an Integer if you don't cast it, and an Integer will never be equal to a Short.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic