Solved

what is the use of overriding hashCode() in java?

Posted on 2011-03-08
12
555 Views
Last Modified: 2012-08-14
Hi All,

while comparing two objects we need over ride the hashCode() method in java, Please explain me in detail, why we need to over ride that method.



0
Comment
Question by:haneef_nb
  • 5
  • 4
  • 2
  • +1
12 Comments
 
LVL 20

Expert Comment

by:a_b
ID: 35069690
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35069693
The idea is so that it behaves properly in the Map classes. Each difference object should produce not only a unique hashcode, but one that makes sense with its purpose and internal structure

http://www.technofundo.com/tech/java/equalhash.html
0
 
LVL 92

Expert Comment

by:objects
ID: 35074836
Theres a contract defined in the javadoc (as explained in the link posted by a_b)
If you change the equals() method, you need to ensure that the hashCode() method still meets that contract.
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

Author Comment

by:haneef_nb
ID: 35089913
Hi All,

Please refer the below code..here i am comparing two stud objects, but it is executes only equals() but not hashCode(), so how can i write in my second app, to execute the hashCode() also
package app;

public class Student {
	int studId;
	String studName;
	int studMarks;

	public Student(int studId, String studName, int studMarks) {
		this.studId = studId;
		this.studName = studName;
		this.studMarks = studMarks;
	}

	public boolean equals(Object o) {
		boolean result = false;
		Student s = (Student) o;
		if (this == o) {
			return true;
		} else {
			result = this.studId == s.studId;
			return result;
		}

	}

	public int hashCode() {
		System.out.println("Hash Code is:" + this.hashCode());
		return this.hashCode();
	}

}

Open in new window

0
 

Author Comment

by:haneef_nb
ID: 35089915

package app;

public class Two 
{
	public static void main(String[] args) {
		
		Student stud1=new Student(100,"Haneef",70);
		Student stud2=new Student(100,"Haneef",80);
		
		
		
		if(stud1.equals(stud2))
			System.out.println("Both are Same");
		else
			System.out.println("Not Same");
			
	}
}

Open in new window

0
 

Author Comment

by:haneef_nb
ID: 35089923
Based on the above two application, by using the equals() method it self, we could compare the two objects, then why we need to call the hashCode() again.
0
 
LVL 92

Expert Comment

by:objects
ID: 35090082
hashCode() is not used for comparing objects, thats what equals() is for. In fact two objects that are equals can have the same hash code.

hashCode() is used for storing Objects in collections like Map's.
0
 
LVL 92

Expert Comment

by:objects
ID: 35090085
0
 

Author Comment

by:haneef_nb
ID: 35119117
Hi Objects,

Thanks..

u r telling it is not for comparing two objects, then why we need to override hashCode() while comparing the two objects.(i think it is mandatory to override)
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 35119200
> then why we need to override hashCode() while comparing the two objects.

you don't

> (i think it is mandatory to override)

its not, but if you override equals then you need to ensure that hashCode() meets the contract defined in the javadoc

- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35122000
Your class should be something like the following, based on your intentions:
public class Student {
    int studId;
    String studName;
    int studMarks;

    public Student(int studId, String studName, int studMarks) {
        this.studId = studId;
        this.studName = studName;
        this.studMarks = studMarks;
    }

    public boolean equals(Object o) {
        boolean result = false;
        Student s = (Student) o;

        if (this == o) {
            result = true;
        } else {
            result = (this.studId == s.studId);
        }

        return result;
    }

    public int hashCode() {
        return studId;
    }
}

Open in new window

0
 

Author Closing Comment

by:haneef_nb
ID: 35228555
It is so help full.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question