1. Address the pitfalls of generics
Question: How do you limit type conversions
Solution: Use wildcards to restrict type conversions
Examples of errors (defects for generics)
List<String> strList = new ArrayList<String>(); List<Integer> intList = new ArrayList<Integer>(); intList.add(123); strList.add("abc"); numberPlus(intList); // numberPlus(strList); Static void numberPlus(List<? extends Number> list){ Number b= 123; //list.add(0,b); Int a = (Integer) list.get(0); a=a+a; System.out.println("numberPlus :" + a); }Copy the code
2. Introduce generic wildcards
Hence the introduction of wildcards
? Super XXX, definition: limit lower limit, can be as small as XXX, call: writable
? Extends XXX, defines: limits a maximum of XXX, calls: readable
3. Best use Cases:
1. Open source framework RxJava map type conversion is used
/ /? Super writable |? Extends public <R> Observable<R> map(Function<? super T, ? extends R> function){ // ObservableMap map = new ObservableMap(source,function); ObservableMap<T, R> observableMap = new ObservableMap(source, function); ObservableMap (observableMap); // observableMap (observableMap); ObservableMap (observableMap); observableMap (observableMap); }Copy the code
Java Collection Copy source code
Is to use the <? Extends T> SRC extends T> SRC extends T> SRC extends T> SRC extends T> SRC extends T> SRC extends T> SRC
Using the < again? Super T> dest is writable, but not readable
SRC is a subclass of dest, so the compiler will check for errors such as:
Collection copy source code
public static <T> void copy(List<? super T> dest, List<? extends T> src) { int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest"); if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); }}}Copy the code