Skip to content

Commit 6835625

Browse files
committed
added generics example method and tests
1 parent 5f99e5a commit 6835625

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class Generics {
5+
6+
// definition of a generic method
7+
public static <T> List<T> fromArrayToList(T[] a) {
8+
List<T> list = new ArrayList<>();
9+
for (T t : a) {
10+
list.add(t);
11+
}
12+
return list;
13+
}
14+
15+
// example of a generic method that has Number as an upper bound for T
16+
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
17+
List<T> list = new ArrayList<>();
18+
for (T t : a) {
19+
list.add(t);
20+
}
21+
return list;
22+
}
23+
24+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.Iterator;
2+
import java.util.List;
3+
4+
import org.junit.Test;
5+
6+
public class GenericsTest {
7+
8+
// testing the generic method with Integer
9+
@Test
10+
public void fromArrayToListIntTest() {
11+
Integer[] intArray = { 1, 2, 3, 4, 5 };
12+
List<Integer> list = Generics.fromArrayToList(intArray);
13+
Iterator<Integer> iterator;
14+
iterator = list.iterator();
15+
while (iterator.hasNext()) {
16+
System.out.println(iterator.next());
17+
}
18+
}
19+
20+
// testing the generic method with String
21+
@Test
22+
public void fromArrayToListStringTest() {
23+
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
24+
List<String> list = Generics.fromArrayToList(stringArray);
25+
Iterator<String> iterator;
26+
iterator = list.iterator();
27+
while (iterator.hasNext()) {
28+
System.out.println(iterator.next());
29+
}
30+
}
31+
32+
// testing the generic method with Number as upper bound with Integer
33+
// if we test fromArrayToListWithUpperBound with any type that doesn't
34+
// extend Number it will fail to compile
35+
@Test
36+
public void fromArrayToListUpperboundIntTest() {
37+
Integer[] intArray = { 1, 2, 3, 4, 5 };
38+
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
39+
Iterator<Integer> iterator;
40+
iterator = list.iterator();
41+
while (iterator.hasNext()) {
42+
System.out.println(iterator.next());
43+
}
44+
}
45+
46+
}

0 commit comments

Comments
 (0)