-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathHashCodeAndEquals.java
112 lines (100 loc) · 2.47 KB
/
HashCodeAndEquals.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* Data-Structures-And-Algorithms-in-Java
* HashCodeAndEquals.java
*/
package com.deepak.data.structures.Hashing;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Implementation for HashCode and Equals contract
*
* @author Deepak
*/
public class HashCodeAndEquals {
/**
* Main method to start the flow
* @param args
*/
public static void main(String[] args) {
Map<Employee, String> cache = loadEmployeeCache();
Employee lookUpKey = new Employee("101", "10111992");
String empName = cache.get(lookUpKey);
System.out.println(empName);
/**
* Set implementation
*/
Set<Employee> employeeSet = new HashSet<>();
Employee e1 = new Employee("100", "10111990");
Employee e2 = new Employee("101", "10111992");
Employee e3 = new Employee("101", "10111992");
Employee e4 = new Employee("102", "10111991");
Employee e5 = new Employee("102", "10111991");
employeeSet.add(e1);
employeeSet.add(e2);
employeeSet.add(e3);
employeeSet.add(e4);
employeeSet.add(e5);
System.out.println(employeeSet);
}
/**
* Method to load employee cache
*/
static Map<Employee, String> loadEmployeeCache() {
Employee e1 = new Employee("100", "10111991");
Employee e2 = new Employee("101", "10111992");
Employee e3 = new Employee("102", "10111993");
Map<Employee, String> cacheMap = new HashMap<>();
cacheMap.put(e1, "Alice");
cacheMap.put(e2, "Bob");
cacheMap.put(e3, "Steve");
return cacheMap;
}
}
/**
* Employee class
*
* @author Deepak
*/
class Employee {
String empId;
String empDob;
/**
* Constructor
* @param id
* @param dob
*/
public Employee(String id, String dob) {
empId = id;
empDob = dob;
}
/**
* HashCode implementation
*/
@Override
public int hashCode() {
int result = empId != null ? empId.hashCode() : 0;
result = 31 * result + (empDob != null ? empDob.hashCode() : 0);
return result;
}
/**
* Equals implementation
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (empDob != null ? !empDob.equals(employee.empDob) : employee.empDob != null) return false;
if (empId != null ? !empId.equals(employee.empId) : employee.empId != null) return false;
return true;
}
/**
* toString() implementation for printing
*/
@Override
public String toString() {
return "Employee [empId=" + empId + ", empDob=" + empDob + "]";
}
}