forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeSetExampleTest.java
More file actions
102 lines (82 loc) · 2.25 KB
/
TreeSetExampleTest.java
File metadata and controls
102 lines (82 loc) · 2.25 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.examplehub.basics.set;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Set;
import java.util.TreeSet;
import org.junit.jupiter.api.Test;
class TreeSetExampleTest {
@Test
void testAdd() {
Set<String> set = new TreeSet<>();
assertTrue(set.add("B"));
assertTrue(set.add("A"));
assertTrue(set.add("C"));
assertTrue(set.add("D"));
assertEquals("[A, B, C, D]", set.toString());
}
@Test
void testComparable() {
class Student implements Comparable<Student> {
private final String name;
private final int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", age=" + age + '}';
}
@Override
public int compareTo(Student o) {
return this.getAge() - o.getAge();
}
}
Student s1 = new Student("Jack", 23);
Student s2 = new Student("Tom", 22);
Student s3 = new Student("Zara", 21);
Set<Student> set = new TreeSet<>();
set.add(s1);
set.add(s2);
set.add(s3);
assertEquals(
"[Student{name='Zara', age=21}, Student{name='Tom', age=22}, Student{name='Jack', age=23}]",
set.toString());
}
@Test
void testComparator() {
class Student {
private final String name;
private final int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
Student s1 = new Student("Jack", 23);
Student s2 = new Student("Tom", 22);
Student s3 = new Student("Zara", 21);
Set<Student> set = new TreeSet<>((o1, o2) -> o1.getAge() - o2.getAge());
set.add(s1);
set.add(s2);
set.add(s3);
assertEquals(
"[Student{name='Zara', age=21}, Student{name='Tom', age=22}, Student{name='Jack', age=23}]",
set.toString());
}
}