- Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathHashSetUserDefinedObjectExample.java
67 lines (55 loc) · 1.51 KB
/
HashSetUserDefinedObjectExample.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
importjava.util.HashSet;
importjava.util.Objects;
importjava.util.Set;
classCustomer {
privatelongid;
privateStringname;
publicCustomer(longid, Stringname) {
this.id = id;
this.name = name;
}
publiclonggetId() {
returnid;
}
publicvoidsetId(longid) {
this.id = id;
}
publicStringgetName() {
returnname;
}
publicvoidsetName(Stringname) {
this.name = name;
}
@Override
publicbooleanequals(Objecto) {
if (this == o) returntrue;
if (o == null || getClass() != o.getClass()) returnfalse;
Customercustomer = (Customer) o;
returnid == customer.id;
}
@Override
publicinthashCode() {
returnObjects.hash(id);
}
@Override
publicStringtoString() {
return"Customer{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
publicclassHashSetUserDefinedObjectExample {
publicstaticvoidmain(String[] args) {
Set<Customer> customers = newHashSet<>();
customers.add(newCustomer(101, "Rajeev"));
customers.add(newCustomer(102, "Sachin"));
customers.add(newCustomer(103, "Chris"));
/*
HashSet will use the `equals()` & `hashCode()` implementations
of the Customer class to check for duplicates and ignore them
*/
customers.add(newCustomer(101, "Rajeev"));
System.out.println(customers);
}
}