• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why aren't these objects considered equal?  RSS feed

 
Kevin Kaminski
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone explain to me why these two objects are considered unequal?




My guess is that though they are both objects of the same type, they're different because they occupy different space in memory. Is this the case here?

If that is the case, what's the point of ever comparing two objects if they'll always have different space in memory?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you haven't override the equals() method. The equals() method inherited from Object only considers the same object equal to itself.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, always use braces with if statements even if the block is only a single line. Leaving them off is a bad practice that will vote you in the rear sooner or later (likely sooner).
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kevin Kaminski wrote:If that is the case, what's the point of ever comparing two objects if they'll always have different space in memory?

Because you can override the equals() method* to mean anything you want with regards to object equality.

String, or example, considers two instances equal if the string contents are the same.



* Note: you should also override hashcode() when overriding equals().
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!