Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

boxing/unboxing operations on equals()

 
Ravinder Singh
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is another one...this time using equals() method.



Object class equals() method is used to test object equality ie. to see if two instances of the same type are "meaningfully equal".

Q. The above doesn't compile saying:

Why int pi in the code above not boxed (wrapped) to an Integer object while invoking equals()? The code compiles and runs when the same expression is changed to i.equals(pi), in which case the argument pi IS wrapped.

Regards
Ravinder
 
GANESHKUMAR Parthsarathi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can not invoke a method from a primitive type. I guss that's the reason.

Correct me if i'm wrong.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Obviously you cannot dereference a primitive. But why is it not boxed and compared with equals?
That in my opinion is a rather inefficient way of doing things.
First box an int then compare the values bitwise of two ints contained in two Integer objects?
Nonsense! The language designers are trying keep the language efficient and try to prevent
the programmer writing code that is "nonsense".

The other way around using Integer.equals() on i and boxing the argument pi from int to Integer. That is (in my opinion) an OK scenario but still inefficient.
i could have been obtained from a Collection and you want to know if it's value is pi. So you would simply have to unbox i and compare it with pi (i.intValue() == pi).
 
Ravinder Singh
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Barry (and Ganesh) for your clarifications...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic