標籤:方便 number arrays ext ble entity 萬用字元 具體化 span
第二十三條:請不要在代碼中使用原生態類型
就是像Set這種待泛型的,就把泛型明確寫出來。
第二十四條:消除非受檢警告
就是Set<String> sets = new HashSet();這種,第二個泛型不加會有一個警告。
第二十五條:列表優先於數組
數組和泛型的區別:
- 數組是協變的。就是如果Sub是Super的子類型,那麼Sub[]就是Super[]的子類型。泛型則是不可變的。
- 數組是可具體化的。一次數組會在運行時才知道並檢查他們的元素類型約束。
第二十六條:優先考慮泛型
類上加上泛型。
第二十七條:優先考慮泛型方法
和上面差不多,寫方法的時候最好能把泛型加上,方便其他人理解,也對類型做了限制跟安全。
interface UnaryFunction<T> { T apply(T arg);}
public class TwentySeventh { private static UnaryFunction<Object> unary = new UnaryFunction<Object>() { @Override public Object apply(Object arg) { return arg; } }; @SuppressWarnings("unchecked") public static <T> UnaryFunction<T> identityFunction() { return (UnaryFunction<T>) unary; } public static void main(String[] args) { String[] strings = {"f", "z", "k"}; UnaryFunction<String> sameString = identityFunction(); for (String string : strings) System.out.println(sameString.apply(string)); Number[] numbers = {1, 2.0, 3L}; UnaryFunction<Number> sameNumber = identityFunction(); for (Number number : numbers) System.out.println(sameNumber.apply(number)); }}
第二十八條:利用有限制萬用字元來提升API的靈活性
public class TwentyEighth { public static <E> Set<E> union(Set<? extends E> s1, Set<? extends E> s2) { Set<E> set = new HashSet<E>(s1); set.addAll(s2); return set; } public static void main(String[] args) { Set<Integer> integers1 = new HashSet<Integer>(Arrays.asList(1, 2, 3)); Set<Integer> integers2 = new HashSet<Integer>(Arrays.asList(1, 2, 3)); Set<Double> doubles = new HashSet<Double>(Arrays.asList(1.0, 2.0, 3.0)); union(integers1, integers2); System.out.println(union(integers1, doubles)); }}
第二十九條:優先考慮型別安全的易購容器
Effective java -- 4 泛型