Everything You Need To know About Java Hashcode

Published on Jul 18,2019 1.3K Views

Everything You Need To know About Java Hashcode

edureka.co

HashMaps and HashSets are used to manipulate data and this is done with the help of hashing. Above approaches use hashCode() method to check and verify hash values. Implementing hashCode() in Object class yields distinct integers for different objects. There are times we may be required to implement hashCode method in our program. In this article we would understand Java hashcode in detail,

This article focuses on following pointers,

So let us get started with the first topic of Java Hashcode article,

What Is Java HashCode?

It returns the hashcode value as an Integer. Hashcode value is mostly used in hashing based collections like HashMap, HashSet, HashTable….etc. This method must be overridden in every class which overrides equals() method.

 The general contract of hashCode() method is:

Let us take a look at a sample code to understand the concept better, however I would suggest starting with Java Installation,

Sample Code For Java Hashcode

public int hashCode()

// This method returns the hash code value 

// for the object on which this method is invoked.

Example

public class Employee {
protected long employeeId;
protected String firstName;
protected String lastName;
public int hashCode(){
return(int)employeeId;
}
}

Notice, that if two Employee objects are equal, they will also have the same hash code. But, as is especially easy to see in the example, two Employee objects can be not equal, and still have the same hash code. There you go, we have successfully explored the concept.

Thus we have come to an end of this article on ‘Java Hashcode’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this article  and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 4th May,2024

4th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial