I have a Movie
class and I override only hashCode()
method. Please find below the java class
public class Movie {
private String actor;
private String name;
private String releaseYr;
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReleaseYr() {
return releaseYr;
}
public void setReleaseYr(String releaseYr) {
this.releaseYr = releaseYr;
}
@Override
public int hashCode() {
return actor.hashCode() + name.hashCode() + releaseYr.hashCode();
}
}
I have created two Movie
objects and both the object's all the property values are same and put them in a HashMap
. Below is the code
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
Movie m1 = new Movie();
m1.setActor("Akshay");
m1.setName("Taskvir");
m1.setReleaseYr("2010");
Movie m2 = new Movie();
m2.setActor("Akshay");
m2.setName("Taskvir");
m2.setReleaseYr("2010");
HashMap<Movie, String> map = new HashMap<Movie, String>();
map.put(m1, "Value of m1");
map.put(m2, "Value of m2");
}
}
I am getting the expected result. As I override only hashCode() method and both the object's hash values are same, so they are stored in the same index location of HashMap table array. Below is the expected result in debugging mode.
But if I do not override the hashCode() method but override the equals() method they are stored in the same index location of HashMap table array. Although I can see the hash values are different. Below is my equals method
@Override
public boolean equals(Object obj) {
Movie m1 = (Movie) obj;
boolean result = false;
if (m1.getActor().equals(this.actor) && m1.getName().equals(this.name)
&& m1.getReleaseYr().equals(this.releaseYr)) {
result = true;
}
return result;
}
The output in debugging mode
If I do not override the equals and hashCode methods then also I am getting same unexpected result.
As per my understanding, if I do not override equals
and hashCode
methods or only override the equals
method then m1
and m2
objects should stored in the different location as hash values are different for m1
and m2
objects. But in this case it is not happening.
Can some one please explain me why with different hash values, my objects stored in the same location?
I have used Java 8.