• 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

equal() and hashcode() method

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


why it is necessary to override equal() and hashcode() in user defined object in collection where as while using wrapper classes object no need to override this two methods?

Thanks in advance

 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The wrapper classes override those two methods for you. For example, see the JavaDoc for Integer. YOu can see it has equals() and hashCode() overridden.

IN your own classes, you need to provide these two methods so the collections classes can call them and see if your objects are equal, belong to the same hash bucket, etc.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to define your own equals() method to define what it means if two objects are equal or not. And the hashCode() method has to be implemented so that when a.equals(b), then a.hashCode() == b.hashCode(). That's necessary if you want to store your objects in a hash-based collection such as HashSet or HashMap. If you don't implement equals() and hashCode() so that the rule I mentioned holds, then you will get unpredictable behaviour if you try to put your objects in for example a HashSet.

The wrapper classes already have their own implementation of hashCode() and equals(). Note that it itsn't possible to override any methods in the wrapper classes (java.lang.Integer, etc.) because these classes are final - if you can't subclass them, then you also can't override anything.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic