Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • 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
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Reg Hashcodes

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

I wanted to compare to objects for equality, and get the hashcode of the objects. I have overridden equals method so that the objects which contain the same data will return true. I read in some book that whenever you override the equals method, you should also override the hashCode method. Can anyone explanin me how to override the hashCode method so that the hashCode values of the objects be equal.

The code is as follows:

public class Equals {
int i;
public Equals(int i){
this.i = i;
}
public boolean equals(Equals obj){
if(obj.i == i)
return true;
else
return false;
}
public int hashCode(){
//Code to write here. so that the two objects which are equal give same hashcode value
}
public static void main(String args[]){
Equals obj1 = new Equals(1);
Equals obj2 = new Equals(1);
System.out.println(obj1.equals(obj2));
}
}

Thanks in Advance.
 
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
Well from what u have written if u want it to return the same hashcode u could simply put return 0; which will ensure that the same number would be returned whenever u call it. There are other techniques though but i guess this would solve ur problem. Cheers.
Saheed.
SCJP 1.4(Coming soon..)
Imagination is better than Knowledge.
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This should answer your question.
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic