Skip to content

Commit b4d25d6

Browse files
Set and HashSet
1 parent bb8fb2c commit b4d25d6

7 files changed

Lines changed: 46 additions & 4 deletions

File tree

1.36 KB
Binary file not shown.
-1.15 KB
Binary file not shown.
-62 Bytes
Binary file not shown.
2.05 KB
Binary file not shown.
1.52 KB
Binary file not shown.

src/TheSet.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import data.PersonModel;
2+
3+
import java.util.HashSet;
4+
import java.util.Iterator;
5+
import java.util.Set;
6+
7+
public class TheSet {
8+
9+
public static void main(String[] args) {
10+
Set<PersonModel> people = new HashSet<>();
11+
12+
people.add(new PersonModel("Dua Lipa", 28));
13+
people.add(new PersonModel("Selena Gomez", 25));
14+
people.add(new PersonModel("Justin Bieber", 18));
15+
people.add(new PersonModel("Selena Gomez", 25));
16+
//people.remove(new PersonModel("Justin Bieber", 18));
17+
18+
System.out.println(people.size());
19+
20+
people.forEach(System.out::println);
21+
22+
System.out.println();
23+
24+
Iterator<PersonModel> iterator = people.iterator();
25+
while (iterator.hasNext()) {
26+
System.out.println(iterator.next());
27+
}
28+
29+
System.out.println();
30+
31+
for (PersonModel person : people) {
32+
System.out.println(person);
33+
}
34+
}
35+
}

src/data/PersonModel.java

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package data;
22

3+
import java.util.Objects;
4+
35
public class PersonModel {
46
private final String name;
57
private final int age;
@@ -9,12 +11,17 @@ public PersonModel(String name, int age) {
911
this.age = age;
1012
}
1113

12-
public String getName() {
13-
return name;
14+
@Override
15+
public boolean equals(Object o) {
16+
if (this == o) return true;
17+
if (o == null || getClass() != o.getClass()) return false;
18+
PersonModel that = (PersonModel) o;
19+
return age == that.age && Objects.equals(name, that.name);
1420
}
1521

16-
public int getAge() {
17-
return age;
22+
@Override
23+
public int hashCode() {
24+
return Objects.hash(name, age);
1825
}
1926

2027
@Override

0 commit comments

Comments
 (0)