Solved

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

Posted on 2011-03-08
12
551 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
 

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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Python Assistance 7 73
what is a "java.lang.System Property"   ? 20 57
Cipher Configuration on Apache HTTPD 4 53
HSSFWorkbook cannot be resolved error 10 50
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This video teaches viewers about errors in exception handling.

895 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

15 Experts available now in Live!

Get 1:1 Help Now