-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathChallenge_27.java
49 lines (39 loc) · 1.24 KB
/
Challenge_27.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
package challenge21_30;
import java.util.HashSet;
import java.util.Set;
/**
* equals and hashcode regarding the use of the HashSet data structure.
*
*/
public class Challenge_27 {
public static void main( String[] args ) {
System.out.println(new Simpson("Bart").equals(new Simpson("Bart")));
final Simpson overriddenSimpson = new Simpson("Homer") {
@Override
public int hashCode() {
return (43 + 777) + 1;
}
};
System.out.println(new Simpson("Homer").equals(overriddenSimpson));
var set = new HashSet<>(Set.of(new Simpson("Homer"), new Simpson("Marge")));
set.add(new Simpson("Homer"));
set.add(overriddenSimpson);
System.out.println(set.size());
}
private static class Simpson {
private String name;
public Simpson( String name ) {
this.name = name;
}
@Override
public boolean equals( Object obj ) {
Simpson otherSimpson = (Simpson) obj;
return this.name.equals(otherSimpson.name)
&& this.hashCode()==otherSimpson.hashCode();
}
@Override
public int hashCode() {
return (43+777);
}
}
}