Effective java -- 4 泛型

來源:互聯網
上載者:User

標籤:方便   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 泛型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.