-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.java
More file actions
81 lines (68 loc) · 1.77 KB
/
Copy pathApp.java
File metadata and controls
81 lines (68 loc) · 1.77 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
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
package tutorial58;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
class Person{
private int id;
private String name;
// hashCode() and equal() methods were auto added from source by eclipse
// necessary as set had duplicates without it
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public Person(int id,String name){
this.id = id;
this.name = name;
}
// had to add this to Person class as print didn't have a toString() method to print it out
public String toString(){
return id + " " + name;
}
}
public class App {
public static void main(String[] args) {
Person p1 = new Person(0,"bob");
Person p2 = new Person(1,"sue");
Person p3 = new Person(2,"mike");
Person p4 = new Person(1,"sue");
Map<Person, Integer> map = new LinkedHashMap<Person, Integer>();
map.put(p1, 1);
map.put(p2, 4);
map.put(p3, 2);
map.put(p4, 3);
for (Person key : map.keySet()) {
System.out.println("key: " + key + " value: " + map.get(key));
}
Set<Person> set = new LinkedHashSet<Person>();
set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
// our set of Persons.. gets printed with the toString() defined in Person class
System.out.println(set);
}
}