zoukankan      html  css  js  c++  java
  • Effective java -- 4 泛型

    第二十三条:请不要在代码中使用原生态类型
    就是像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));
      }
    }

    第二十九条:优先考虑类型安全的易购容器

  • 相关阅读:
    EntityFramework优缺点
    领导者与管理者的区别
    七个对我最好的职业建议(精简版)
    The best career advice I’ve received
    Difference between Stored Procedure and Function in SQL Server
    2015年上半年一次通过 信息系统项目管理师
    Difference between WCF and Web API and WCF REST and Web Service
    What’s the difference between data mining and data warehousing?
    What is the difference between a Clustered and Non Clustered Index?
    用new创建函数的过程发生了什么
  • 原文地址:https://www.cnblogs.com/badboyf/p/6290350.html
Copyright © 2011-2022 走看看