Solved

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

Posted on 2011-03-08
12
562 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 

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

Major Incident Management Communications

Major incidents and IT service outages cost companies millions. Often the solution to minimizing damage is automated communication. Find out more in our Major Incident Management Communications infographic.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
check java version using powershell 13 442
ejb wildfly example 2 106
spring maven example issues 3 93
Pass multiple values or string arrays in java as a parameter 3 72
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

738 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