• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

conditional check code usage in equals & hashCode

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys,

I have a question that i would like some feedback on. Take a look at the following code fragments:


Example A:

public boolean equals(Object obj) {
if(this == obj)
return true;

// 1st conditional check

if(obj == null) || (obj.getClass() != this.getClass()))
return false;

Example B:

public boolean equals(Object obj) {
if(this == obj)
return true;

// 2nd conditional check

if(!(obj instanceof Test)) return false;


My question is wouldn't the 1st conditional check be best to use in case the argument is a subclass of the superclass? It is my understanding that the 'instanceof' operator wouldn't return false.



Thanks in advance......



Also, to the moderators.....i wasn't sure which forum this question would be best served in, so forgive me if I broke any rules.
 
Sheriff
Posts: 22656
126
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
instanceof can be dangerous; if used improperly, you can break one of the rules for equals: if x.equals(y), then y.equals(x) should be true.

Consider the following piece of code:

Now if class A is final, or the equals method is final, there's no big issue. But otherwise, it is very well possible to break the contract in a sub class. You might not do it, but someone else still can.

Now if you use the Class comparison, then a.equals(b) will be false as well, therefore not breaking the contract.
 
Derek Harper
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Rob!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic