• Post Reply Bookmark Topic Watch Topic
  • New Topic

.equals and == in Integer/Double  RSS feed

 
Rajesh Santhanakrishnan
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

For Integer class, if I compare 2 objects with == , it compares the values of the object, but for Double,it compares only the location of the objects rather than values.
I can overcome in Double object by overriding .equals method. But my question is though both Integer/Double are classes and both implement .equals, why == works fine for Integer object and not for Double.
Any ideas?


 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When a primitive is auto-boxed, it actually calls the valueOf method of the matching wrapper class. For integer types (byte, short, int, long), values from -128 to 127 (inclusive) are usually cached. That means that you can use == to compare them for these values. Other values will fail however; just try it with 128.

For float and double, there is no such caching (because there are simply waaaaayyyyy too many values). That means that each auto-boxed value will be a new object, and those do not compare well with ==.


The best strategy is too simply not use == when any object type is involved, but instead use the equals method (or Objects.equals to be null-safe).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!