| Author |
equals or identity
|
nimo frey
Ranch Hand
Joined: Jun 28, 2008
Posts: 580
|
|
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
Joined: Oct 27, 2005
Posts: 19230
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Saifuddin Merchant
Ranch Hand
Joined: Feb 08, 2009
Posts: 576
|
|
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?
|
Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
|
 |
nimo frey
Ranch Hand
Joined: Jun 28, 2008
Posts: 580
|
|
|
okay thank you!
|
 |
nimo frey
Ranch Hand
Joined: Jun 28, 2008
Posts: 580
|
|
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
Joined: Aug 05, 2005
Posts: 3011
|
|
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.
|
Joanne
|
 |
 |
|
|
subject: equals or identity
|
|
|