Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Checking equality of objects

 
Tresa Antony
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Could you please tell me why this equality check results in 'false' ?


Ta much
 
Joseph Maddison
Ranch Hand
Posts: 53
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, it's a little tricky. Strings are not primitives-- they're objects. Primitives compare as you'd expect with ==, but with objects, == compares addresses in memory, so unless you're comparing an object with itself, it won't be equal.

For objects comparision, there are two parts-- first, make sure that it is not null, and then call the equals() method on it. So, something like



Hope This Helps,
jdmaddison
 
Tresa Antony
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Refering to my query on equality -

So each time i invoke b1.toString(), does it create a new String object in memory?
 
Qunfeng Wang
Ranch Hand
Posts: 434
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah.
I think so.
 
David Harkness
Ranch Hand
Posts: 1646
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tresa Antony:
So each time i invoke b1.toString(), does it create a new String object in memory?
It depends on the class's implementation of toString(). Typically, the answer is yes (for example with Byte and Integer, etc), but some classes either already have a String they can return -- say an Employee class that returns the employee's first name-- or store the built String to be returned for future calls. This latter case is used when building the String representation is very expensive and performance is critical, but it's pretty rare.

In these two cases multiple calls to toString() return the same String, but I cannot stress enough that you should not depend on this behavior since the implementation can be changed or the class could be subclassed, both without you ever knowing. Use the equals() method and you'll never have to worry about it. There's also equalsIgnoreCase() if you need case-insensitive comparisons.

Another good example is String's toString():
[ January 28, 2005: Message edited by: David Harkness ]
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic