What is equals() and hashCode() Method in Java? | What are use of equals() and hashCode() Method in Java
Java hashCode() and equals() Methods with Examples | When to use | How to Use
You already known that Object is root of all classes in Java.
So whenever we create any class in java then our class implicitly extends the Object class.
There are so many methods available in Object.
- clone()
- equals()
- finalize()
- getClass()
- hashCode()
- notify()
- notifyAll()
- toString()
- wait()
Check out this Java doc above methods
Now in this article we talk about equals() and hashCode() method. so lets start.
So first question in your mind pop up that why i use equals and hashCode method so lets see answer of that first.
Why and in which condition we have to use equals() and hashCode() method in Java?
- When we want to use Object as key in hashTable then we should use equals() and hashCode() methods in java.
equals() Method
In simple term, equals() method checks that one object is 'equals to' another object.
equals() method used to simply verify the equality of two objects. It's default implementation simply check the object references of two objects to verify their equality.
By default, two object are equals if and only if they are stored in same memory address.
for any non-null reference values x and y, equals() method returns true if only x and y refer to the same object (x == y has the value true).
Lets see example of default behavior of equals() method.
Example 1 :- Default implementation of equals() method
User.java
public class User {
int id;
String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
EqualsAandHashcode.java
public class EqualsAandHashcode {
public static void main(String[] args) {
User user1 = new User(1, "user1");
User user2 = new User(1, "user1");
System.out.println(user1.equals(user2));
}
}
Output :-
false
So you can seen in above example, that we declare two objects with same id and name, but when we check equals() of that we get output false. but in real time application we have to get true, because it is same object.
So now we override equals method and check what we get.
Example 2 :- Override equals() method.
User.java
public class User {
int id;
String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
EqualsAandHashcode .java
public class EqualsAandHashcode {
public static void main(String[] args) {
User user1 = new User(1, "user1");
User user2 = new User(1, "user1");
System.out.println(user1.equals(user2));
}
}
Output :-
true
Now after override equals method we get true for same object. so it is very important in real time java application that we should implement equals() method.
If you want to generate equals and hashCode method then right click on your eclipse and go to -> Source -> Generate hashCode() and equals().
For above example you can comment hashCode() method.
hashCode() Method
What is hashCode() method? Why we use hashCode() method in java?
The hashCode() mehod of object is used when we use HashTable, HashMap and HashSet.
When inserting an object into hashtable we use a key. The hashcode of this key is calculated, and used to determine where to store the object internally.
When we need to lookup an object in a hashtable we also use a key. The hashcode of this key is calculated and used to determine where to search for an object.
So lets see example what happens if we does not use hashCode() method.
Example 3 :- Without overriding hashCode() method
public class User {
int id;
String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
public class EqualsAandHashcode {
public static void main(String[] args) {
User user1 = new User(1, "user1");
User user2 = new User(1, "user1");
System.out.println(user1.equals(user2));
Set<User> setOfUser = new HashSet<>();
setOfUser.add(user1);
setOfUser.add(user2);
System.out.println(setOfUser);
}
}
Output :-
true
[User [id=1, name=user1], User [id=1, name=user1]]
You know that Set does not contains duplicate value but in above example you can clearly see we got two object. So what happens when we use hashCode() method? so lets implement it.
Example 4 :- overriding hashCode() method in Java
public class User {
int id;
String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
public class EqualsAandHashcode {
public static void main(String[] args) {
User user1 = new User(1, "user1");
User user2 = new User(1, "user1");
System.out.println(user1.equals(user2));
Set<User> setOfUser = new HashSet<>();
setOfUser.add(user1);
setOfUser.add(user2);
System.out.println(setOfUser);
}
}
Output :-
true
[User [id=1, name=user1]]
So after overriding hashCode() method we can clearly see we get only one object that have same id and name.
So, both equals() and hashCode() methods are important in our java real time application.
If you want to learn about equals() and hashCode() method, What is contract between them? Read out these articles. i also taken references from these articles and video.
- https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html
- https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java
- https://dzone.com/articles/working-with-hashcode-and-equals-in-java
- https://www.journaldev.com/21095/java-equals-hashcode
- http://tutorials.jenkov.com/java-collections/hashcode-equals.html
- https://www.youtube.com/watch?v=HRHMkQ9fWsM
- Double Brace Initialization in Java
- BiFunction in Java
- Lambda Expression in Java
- Functional Interface in Java
- Abstraction in Java
- Static in Java (Static class, Method, Variable and Block)
- Final keyword in java
- Difference between Final, Finally and Finalize in Java
Comments
Post a Comment