Basics Of Java Generics
这里是这篇文章的随笔记录:https://www.baeldung.com/java-generics , 内容非常基础,可参考原文。如果想了解关于泛型更深入的,可以参考这篇:http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html (非常详细)
1. The Basics:
1.1 Generic Methods
demo1:
public <T> List<T> fromArrayToList(T[] a) { return Arrays.stream(a).collect(Collectors.toList()); }
The <T> in the method signature implies that the method will be dealing with generic type T. This is needed even if the method is returning void.
As mentioned, the method can deal with more than one generic type. Where this is the case, we must add all generic types to the method signature.
Here is how we would modify the above method to deal with type T and type G:
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) { return Arrays.stream(a) .map(mapperFunction) .collect(Collectors.toList()); }
@Test public void givenArrayOfIntegers_thanListOfStringReturnedOK() { Integer[] intArray = {1, 2, 3, 4, 5}; List<String> stringList = Generics.fromArrayToList(intArray, Object::toString); assertThat(stringList, hasItems("1", "2", "3", "4", "5")); }
1.2 Bounded Generics
public <T extends Number> List<T> fromArrayToList(T[] a) { ... }
1.3 wildcard with Generics
public static void paintAllBuildings(List<Building> buildings) { buildings.forEach(Building::paint); }
public static void paintAllBuildings(List<? extends Building> buildings) { ... }
2. Generic Class
// Java program to show multiple // type parameters in Java Generics // We use < > to specify Parameter type class Test<T, U> { T obj1; // An object of type T U obj2; // An object of type U // constructor Test(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } // To print objects of T and U public void print() { System.out.println(obj1); System.out.println(obj2); } } // Driver class to test above class Main { public static void main (String[] args) { Test <String, Integer> obj = new Test<String, Integer>("GfG", 15); obj.print(); } }

浙公网安备 33010602011771号