You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/main/java/com/ab/collection/maps/HashCodeEqualsContract.java
+12-2Lines changed: 12 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -6,6 +6,16 @@
6
6
importjava.util.Map;
7
7
importjava.util.Objects;
8
8
9
+
/**
10
+
* @author Arpit Bhardwaj
11
+
*
12
+
* Contract:
13
+
* If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
14
+
*
15
+
* It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results.
16
+
* However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
17
+
*/
18
+
9
19
publicclassHashCodeEqualsContract {
10
20
staticclassProduct{
11
21
privatefinalStringname;
@@ -29,7 +39,6 @@ public String toString() {
29
39
return"Product{ "+name+":"+weight+" }";
30
40
}
31
41
32
-
33
42
@Override
34
43
publicbooleanequals(Objecto) {
35
44
if (this == o) returntrue;
@@ -39,7 +48,6 @@ public boolean equals(Object o) {
39
48
Objects.equals(name, product.name);
40
49
}
41
50
42
-
43
51
@Override
44
52
publicinthashCode() {
45
53
returnObjects.hash(name, weight);
@@ -56,11 +64,13 @@ public static void main(String[] args) {
56
64
map.put(p3,3456);
57
65
58
66
//implement only equals
67
+
//default hasCode() impl returns distinct integer for distinct object
59
68
//you will not able to retrieve what you have added as the logical equal products have different hashcode
60
69
Productp4 = newProduct("P2",24);
61
70
System.out.println(map.get(p4));
62
71
63
72
//implement only hashcode
73
+
//default equals() impl returns true only if two objects had the same reference pointer
64
74
//you can add duplicate keys which are logically equal
65
75
//also you will not able to retrieve what you have added as the logical equal products have different hashcode
0 commit comments