Solved

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

Posted on 2011-03-08
12
547 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
Comment Utility
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
Comment Utility
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
 

Author Comment

by:haneef_nb
Comment Utility
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
Comment Utility

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
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 92

Expert Comment

by:objects
Comment Utility
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
Comment Utility
0
 

Author Comment

by:haneef_nb
Comment Utility
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
Comment Utility
> 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
Comment Utility
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
Comment Utility
It is so help full.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

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…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

771 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now