added generics example method and tests
This commit is contained in:
parent
5f99e5aedd
commit
6835625602
|
@ -0,0 +1,24 @@
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Generics {
|
||||||
|
|
||||||
|
// definition of a generic method
|
||||||
|
public static <T> List<T> fromArrayToList(T[] a) {
|
||||||
|
List<T> list = new ArrayList<>();
|
||||||
|
for (T t : a) {
|
||||||
|
list.add(t);
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
// example of a generic method that has Number as an upper bound for T
|
||||||
|
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
|
||||||
|
List<T> list = new ArrayList<>();
|
||||||
|
for (T t : a) {
|
||||||
|
list.add(t);
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,46 @@
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class GenericsTest {
|
||||||
|
|
||||||
|
// testing the generic method with Integer
|
||||||
|
@Test
|
||||||
|
public void fromArrayToListIntTest() {
|
||||||
|
Integer[] intArray = { 1, 2, 3, 4, 5 };
|
||||||
|
List<Integer> list = Generics.fromArrayToList(intArray);
|
||||||
|
Iterator<Integer> iterator;
|
||||||
|
iterator = list.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
System.out.println(iterator.next());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// testing the generic method with String
|
||||||
|
@Test
|
||||||
|
public void fromArrayToListStringTest() {
|
||||||
|
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
|
||||||
|
List<String> list = Generics.fromArrayToList(stringArray);
|
||||||
|
Iterator<String> iterator;
|
||||||
|
iterator = list.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
System.out.println(iterator.next());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// testing the generic method with Number as upper bound with Integer
|
||||||
|
// if we test fromArrayToListWithUpperBound with any type that doesn't
|
||||||
|
// extend Number it will fail to compile
|
||||||
|
@Test
|
||||||
|
public void fromArrayToListUpperboundIntTest() {
|
||||||
|
Integer[] intArray = { 1, 2, 3, 4, 5 };
|
||||||
|
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
|
||||||
|
Iterator<Integer> iterator;
|
||||||
|
iterator = list.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
System.out.println(iterator.next());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue