[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

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

Posted on 2011-03-08
12
Medium Priority
?
567 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 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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
 

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 2000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses

649 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