forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericExampleTest.java
More file actions
64 lines (54 loc) · 1.63 KB
/
GenericExampleTest.java
File metadata and controls
64 lines (54 loc) · 1.63 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
package com.examplehub.basics.generic;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class GenericExampleTest {
@Test
void testNoGeneric() {
List list = new ArrayList();
list.add("hello");
list.add(123);
list.add(12.34);
assertEquals("[hello, 123, 12.34]", list.toString());
assertEquals("hello", (String) list.get(0));
assertEquals(123, (int) list.get(1));
assertEquals(12.34, (double) list.get(2));
try {
String num = (String) list.get(1);
fail();
} catch (ClassCastException e) {
assertTrue(true);
}
}
@Test
void testGenericList() {
List<String> list = new ArrayList<>();
list.add("java");
// list.add(123); //compile error
list.add("python");
assertEquals("[java, python]", list.toString());
}
@Test
void testGenericInterface() {
class Student implements Comparable<Student> {
private String name;
private int age;
@Override
public int compareTo(Student o) {
return Integer.compare(this.age, o.age);
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
assertTrue(new Student("jack", 20).compareTo(new Student("tom", 21)) < 0);
assertTrue(new Student("jack", 22).compareTo(new Student("tom", 21)) > 0);
assertTrue(new Student("jack", 20).compareTo(new Student("tom", 20)) == 0);
String[] languages = {"java", "python", "cpp"};
Arrays.sort(languages);
assertEquals("[cpp, java, python]", Arrays.toString(languages));
}
}