forked from TimSongCoder/LearnJavaForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomClassAndHashSet.java
More file actions
56 lines (47 loc) · 1.19 KB
/
Copy pathCustomClassAndHashSet.java
File metadata and controls
56 lines (47 loc) · 1.19 KB
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
import java.util.Set;
import java.util.HashSet;
public class CustomClassAndHashSet{
public static void main(String[] args){
Set<Planet> sp = new HashSet<Planet>();
sp.add(new Planet("Mercury"));
sp.add(new Planet("Venus"));
sp.add(new Planet("Earth"));
sp.add(new Planet("Mars"));
sp.add(new Planet("Jupiter"));
sp.add(new Planet("Saturn"));
sp.add(new Planet("Uranus"));
sp.add(new Planet("Neptune"));
sp.add(new Planet("Fomalhaut b"));
Planet p1 = new Planet("51 pegasi b");
sp.add(p1);
Planet p2 = new Planet("51 pegasi b");
sp.add(p2);
System.out.println("EQUALS: " + p1.equals(p2));
System.out.println("HASHCODE: " + (p1.hashCode() == p2.hashCode()));
// Duplicate check both equals and hashCode.
System.out.println(sp);
}
}
class Planet{
private String name;
Planet(String name){
this.name = name;
}
@Override
public boolean equals(Object o){
if( !(o instanceof Planet)){
return false;
}
Planet p = (Planet)o;
return this.name.equals(p.name);
}
String getName(){
return name;
}
public String toString(){
return name;
}
public int hashCode(){
return name.hashCode(); // Because String implements the hashCode method validly.
}
}