Skip to content

Commit 49edc7d

Browse files
author
Pankaj Kumar
committed
Java equals() and hashCode() implementation example
1 parent 27ce65b commit 49edc7d

File tree

3 files changed

+113
-0
lines changed

3 files changed

+113
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<groupId>com.journaldev.java</groupId>
6+
<artifactId>Java-Equals-Hashcode</artifactId>
7+
<version>0.0.1-SNAPSHOT</version>
8+
9+
<build>
10+
<plugins>
11+
<plugin>
12+
<groupId>org.apache.maven.plugins</groupId>
13+
<artifactId>maven-compiler-plugin</artifactId>
14+
<version>3.7.0</version>
15+
<configuration>
16+
<release>10</release>
17+
</configuration>
18+
</plugin>
19+
</plugins>
20+
</build>
21+
22+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.journaldev.java;
2+
3+
public class DataKey {
4+
5+
private String name;
6+
private int id;
7+
8+
public String getName() {
9+
return name;
10+
}
11+
12+
public void setName(String name) {
13+
this.name = name;
14+
}
15+
16+
public int getId() {
17+
return id;
18+
}
19+
20+
public void setId(int id) {
21+
this.id = id;
22+
}
23+
24+
@Override
25+
public int hashCode() {
26+
final int prime = 31;
27+
int result = 1;
28+
result = prime * result + id;
29+
result = prime * result + ((name == null) ? 0 : name.hashCode());
30+
return result;
31+
}
32+
33+
@Override
34+
public boolean equals(Object obj) {
35+
if (this == obj)
36+
return true;
37+
if (obj == null)
38+
return false;
39+
if (getClass() != obj.getClass())
40+
return false;
41+
DataKey other = (DataKey) obj;
42+
if (id != other.id)
43+
return false;
44+
if (name == null) {
45+
if (other.name != null)
46+
return false;
47+
} else if (!name.equals(other.name))
48+
return false;
49+
return true;
50+
}
51+
52+
@Override
53+
public String toString() {
54+
return "DataKey [name=" + name + ", id=" + id + "]";
55+
}
56+
57+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.journaldev.java;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class HashingTest {
7+
8+
public static void main(String[] args) {
9+
Map<DataKey, Integer> hm = getAllData();
10+
11+
DataKey dk = new DataKey();
12+
dk.setId(1);
13+
dk.setName("Pankaj");
14+
System.out.println(dk.hashCode());
15+
16+
Integer value = hm.get(dk);
17+
18+
System.out.println(value);
19+
20+
}
21+
22+
private static Map<DataKey, Integer> getAllData() {
23+
Map<DataKey, Integer> hm = new HashMap<>();
24+
25+
DataKey dk = new DataKey();
26+
dk.setId(1);
27+
dk.setName("Pankaj");
28+
System.out.println(dk.hashCode());
29+
hm.put(dk, 10);
30+
31+
return hm;
32+
}
33+
34+
}

0 commit comments

Comments
 (0)