7. Example for Bounded Wildcard Type
Example:
class Stack {
public Stack();
public void push(E e);
public E pop();
public boolean isEmpty();
}
想要新增 pushAll() 及 popAll()
15. PECS:幫你解決轉換的困擾
public static <T extends Comparable<T>> T max(List<T> list) {
public static <T extends Comparable<? super T>> T max(List<? extends T> list)
max() 裡面用到:
1. Iterator<T> i = list.iterator();
2. t.compareTo(result)
list 提供元素,是生產者
t 獲取元素進行比較,是消費者
17. 隱藏類型參數 1/3
public static <E> void swap(List<E> list, int i, int j)
public static void swap(List<?> list, int i, int j)
Which one is better?
18. 隱藏類型參數 2/3
public static void swap(List<?> list, int i, int j) {
list.set(i, list.set(j, list.get(i))); // compile error
}
List<?>
compiler 完全不知道裡面放什麼類型
19. 隱藏類型參數 3/3
public static void swap(List<?> list, int i, int j) {
swapHelper(list, i, j);
}
// for wildcard capture
private static <E> void swapHelper(List<E> list, int i, int j) {
list.set(i, list.set(j, list.get(i)));
}
20. 異構容器 (heterogeneous container)
Type Token 概念,以 type 為 key 存取值
public class Favorite {
public <T> void putFavorite(Class<T> type, T instance);
public <T> T getFavorite(Class<T> type);
}
fav.put(String.class, “XD”);
fav.put(Integer.class, 20);
fav.get(String.class); “XD”
21. 實作範例 - 利用動態 cast
public class Favorite {
private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>();
public <T> void putFavorite(Class<T> type, T instance) {
// check type null
favorites.put(type, type.cast(instance));
}
public <T> T getFavorite(Class<T> type) {
return type.cast(favorites.get(type));
}
}
若 client 誤用,可拋出ClassCastException
拿出來是 Object 類型,但回傳值要求 T 類型