• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

equals( ) method: use of instanceof

 
blacksmith
Posts: 979
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I've read it's good practice to use the instanceof
operator to check whether the passed reference to
an object is indeed an instance of the class of the
object it's compared to.
Since instanceof gives an exception if the passed
reference to an object does not belong to the same
class hierarchy, is it also good practice to
surround this test by a try catch block handling
this exception?
Thanks, greetings
Gian Franco
 
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
instanceof will cause a compile error if the argument to instanceof cannot possibly be the same class type as the reference type.
No amount of trying and catching will prevent this.
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the case of the equals method, the instanceof operator will never cause an error. Why not? Well, because the parameter of equals is of type Object and everything is a subclass of Object. Therefore, instanceof will always work within the equals method.
 
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A better idea is to use getClass() instead of instanceof operator. The instanceof operator will return true even if the RHS is a subclass of the expected class. This might create problems if subclass compexly changes state of the object. See relevant stuff from Java Rules by Douglous Dunn.
This article also attempts to explain the same.
One such bad example is java.sql.Timestamp, which is a subclass of java.util.Date; and I believe it does explictly mention abt equals violation in its documentation.
HTH,
- Manish
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic