关于java:Java泛型最佳实践

2次阅读

共计 12073 个字符,预计需要花费 31 分钟才能阅读完成。

前言

置信大家对 Java 泛型并不生疏,无论是开源框架还是 JDK 源码都能看到它,毫不夸大的说,泛型是通用设计上必不可少的元素,所以真正了解与正确应用泛型,是一门必修课,本文将解开大家对泛型的纳闷,并通过大量实际,让你 get 到泛型正确的应用姿态,上面开始进入正题吧!

纲要

根底

因为本文重实际,而且面对的是 Java 开发人员群体,大家对泛型都有根底,所以泛型根底这块会疾速过,帮忙大家回顾下即可,前面次要的则重点是通配符

编译期与运行期

编译期 是指把源码交给编译器编译成计算机可执行文件的过程,运行期 是指把编译后的文件交给计算机执行,直到程序完结。

Java 中就是把 .java 文件编译成 .class 文件,再把编译后的文件交给 J V M 加载执行,如下图

泛型

泛型又叫“参数化类型”,这么形象的业余词汇不好了解,阿星就用大白话的模式来解释。

人是铁,饭是刚,吃饭是刚需,要吃饭天然就少不了碗筷,然而没有规定碗只能盛饭,除了盛饭它还能盛汤、盛菜,制造者只造这个碗,不关怀碗盛什么,具体要盛什么由使用者来决定,这就是泛型的概念。

泛型就是在定义类、接口、办法的时候指定某一种特定类型(碗),让类、接口、办法的使用者来决定具体用哪一种类型的参数(盛的货色)。

Java的泛型是在 1.5 引入的,只在 编译期 做泛型查看,运行期 泛型就会隐没,咱们把这称为“泛型擦除”,最终类型都会变成 Object

在没有泛型之前,从汇合中读取到的每一个对象都必须进行类型转换,如果不小心插入了谬误的类型对象,在运行时的转换解决就会出错,有了泛型后,你能够通知编译器每个汇合接管的对象类型是什么,编译器在编译期就会做类型查看,告知是否插入了谬误类型的对象,使得程序更加平安,也更加分明。

最初插一句,泛型擦除与原生态类型(List 就是原生态,List<T> 非原生态)是为了关照 1.5 以前设计上的缺点,为兼容非泛型代码,所作出的折中策略,所以不举荐应用原生态类型,如果应用了原生态类型,就失去了泛型在安全性与描述性方面的劣势。

泛型类

类上定义泛型,作用于类的成员变量与函数,代码实例如下

public class GenericClass<T>{
    // 成员变量
    private T t;
    
    public  void function(T t){ }
    
    public T functionTwo(T t){
        // 留神,这个不是泛型办法!!!return t;
    }
}

泛型接口

接口上定义泛型,作用于函数,代码实例如下

public interface GenericInterface<T> {public T get();
    
    public void set(T t);

    public T delete(T t);
    
    default T defaultFunction(T t){return t;}
}

泛型函数

函数返回类型旁加上泛型,作用于函数,代码实例如下

public class GenericFunction {public <T> void function(T t) { }

    public <T> T functionTwo(T t) {return t;}

    public <T> String functionThree(T t) {return "";}
}

通配符

通配符是为了让 Java 泛型反对范畴限定,这样使得泛型的灵活性晋升,同时也让通用性设计有了更多的空间。

  • <?>:无界通配符,即类型不确定,任意类型
  • <? extends T>:上边界通配符,即 ? 是继承自 T 的任意子类型,恪守只读不写
  • <? super T>:下边界通配符,即 ?T的任意父类型,恪守只写不读

置信大部分人,都是倒在通配符这块,这里多唠叨点,「通配符限定的范畴是体现在确认“参数化类型”的时候,而不是“参数化类型”填充后」,可能这句话不太好了解,来看看上面的代码

/**
 * 1. 创立泛型为 Number 的 List 类,Integer、Double、Long 等都是 Number 的子类
 *   new ArrayList<>() 等价于 new ArrayList<Number>()
 */
List<Number> numberList = new ArrayList<Number>();

/**
 * 2. 增加不同子类
 */
numberList.add(1);// 增加 Integer 类型
numberList.add(0.5);// 增加 Double 类型
numberList.add(10000L);// 增加 Long 类型

/**
 * 3. 创立泛型为 Number 的 List 类,Integer、Double、Long 等都是 Number 的子类
 *   援用是泛型类别是 Number,但具体实现指定的泛型是 Integer
 */
List<Number> numberListTwo = new ArrayList<Integer>();//err 异样编译不通过

/**
 * 4. 创立泛型为 Integer 的 List 类,把该对象的援用地址指向泛型为 Number 的 List
 */
List<Integer> integerList = new ArrayList<Integer>();
List<Number> numberListThree = integerList;//err 异样编译不通过
  • 第一步:咱们创立一个泛型为 NumberList,编译器查看泛型类别是否统一,统一编译通过(确认参数化类型)
  • 第二步:泛型 Number 曾经填充结束,调用 add 函数,此时 add 入参泛型 T 曾经填充为 Numberadd 可入参 Number 或其子类
  • 第三步:咱们又创立一个泛型为 NumberList,编译器查看泛型类别是否统一,不统一编译失败,提醒谬误(确认参数化类型)
  • 第四步:其实与第三步一样,只是做了一个间接的援用(确认参数化类型)

如果要解决下面的编译不通过问题,就须要应用通配符,代码如下

/**
 * 1. 上边界通配符,Number 与 Number 子类
 */
List<? extends Number> numberListFour = new ArrayList<Number>();
numberListFour = new ArrayList<Integer>();
numberListFour = new ArrayList<Double>();
numberListFour = new ArrayList<Long>();

/**
 * 2. 下边界通配符,Integer 与 Integer 父类
 */
List<? super Integer> integerList = new ArrayList<Integer>();
integerList = new ArrayList<Number>();
integerList = new ArrayList<Object>();

/**
 * 3. 无界通配符, 类型不确定,任意类型
 */
List<?> list = new ArrayList<Integer>();
list = new ArrayList<Number>();
list = new ArrayList<Object>();
list = new ArrayList<String>();

最初再来说上边界通配符只读不写,下边界通配符只写不读到底是什么意思,用最简略的话来说

  • <? extends T>上边界通配符不作为函数入参,只作为函数返回类型,比方 List<? extends T> 的应用 add 函数会编译不通过,get函数则没问题
  • <? super T>下边界通配符不作为函数返回类型,只作为函数入参,比方 List<? super T>add函数失常调用,get函数也没问题,但只会返回Object,所以意义不大

大家只须要记住下面的规定即可,如果想晓得为什么这样设计,能够去理解下 P E C S (producer-extends,consumer-super) 准则

最佳实际

置信过完基础理论大家很多货色都回顾起来了,不要焦急,当初开始进入正题,前面内容会有大量的代码实际,所以大家要坐稳了,别晕车了,晕车的话多看几遍,或者评论区提出你的疑难~

有限通配符场景

应用泛型,类型参数不确定并且不关怀理论的类型参数,就能够应用<?>,像上面的代码

/**
 * 获取汇合长度
 */
public static <T> int size(Collection<T> list){return list.size();
}

/**
 * 获取汇合长度 -2
 */
public static int sizeTwo(Collection<?>  list){return list.size();
}


/**
 * 获取任意 Set 两个汇合交加数量
 */
public static <T,T2> int beMixedSum(Set<T> s1,Set<T2> s2){
    int i = 0;
    for (T t : s1) {if (s2.contains(t)) {i++;}
    }
    return i;
}

/**
 * 获取任意两个 Set 汇合交加数量 -2
 */
public static  int beMixedSumTwo(Set<?> s1,Set<?> s2){
    int i = 0;
    for (Object o : s1) {if (s2.contains(o)) {i++;}
    }
    return i;
}

sizesizeTwo 这两个函数都能够失常应用,然而站在设计的角度,sizeTwo会更适合,函数的指标是返回任意汇合的长度,入参采纳 <T><?>都能够接管,然而函数自身并不关怀你是什么类型参数,仅仅只有返回长度即可,所以采纳<?>

beMixedSumbeMixedSumTwo 这两个函数比拟,情理同下面一样,beMixedSumTwo会更适合,函数的指标是返回两个任意 Set 汇合的交加数量,beMixedSum函数尽管外部有应用到 <T>,然而意义不大,因为contains 入参是Object,函数自身并不关怀你是什么类型参数,所以采纳<?>

忘了补充另一个场景,就是原生态类型,上述代码应用原生态类型函数应用也没问题,然而强烈不举荐,因为应用原生态就失落了泛型带来的安全性与描述性!!!

高低边界通配符场景

首先泛型是不变的,换句话说List<Object> != List<String>,有时候须要更多灵活性,就能够通过高低边界通配符来做晋升。

/**
 * 汇合工具类
 */
public class CollectionUtils<T>{
        
    /**
     * 复制汇合 - 泛型
     */
    public List<T>  listCopy(Collection<T> collection){List<T> newCollection = new ArrayList<>();
        for (T t : collection) {newCollection.add(t);
        }
        return newCollection;
    }
    
}

下面申明了一个 CollectionUtils 类,领有 listCopy 办法,传入任意一个汇合返回新的汇合,看似没有什么问题,也很灵便,那再看看上面这段代码。

public static void main(String[] agrs){CollectionUtils<Number> collectionUtils = new CollectionUtils<>();
    List<Number>  list = new ArrayList<>();
    //list.add....
    List<Integer>  listTwo = new ArrayList<>();
    //listTwo.add....
    List<Double>  listThree = new ArrayList<>();
    //listThree.add....

    List<Number> list1 = collectionUtils.listCopy(list);
    list1 = collectionUtils.listCopy(listTwo);//err 编译异样
    list1 = collectionUtils.listCopy(listThree);//err 编译异样
}

创立 CollectionUtils 类,泛型的类型参数为 NumberlistCopy 函数入参的泛型填充为 Number,此时listCopy 只反对泛型为 NumberList,如果要让它同时反对泛型为 Number 子类的List,就须要应用上边界通配符,咱们再追加一个办法

/**
 * 汇合工具
 */
public class CollectionUtils<T>{
        
    /**
     * 复制汇合 - 泛型
     */
    public List<T>  listCopy(Collection<T> collection){List<T> newCollection = new ArrayList<>();
        for (T t : collection) {newCollection.add(t);
        }
        return newCollection;
    }
    
    /**
     * 复制汇合 - 上边界通配符
     */
    public  List<T>  listCopyTwo(Collection<? extends T> collection){List<T> newCollection = new ArrayList<>();
        for (T t : collection) {newCollection.add(t);

        }
        return newCollection;
    }
}

public static void main(String[] agrs){CollectionUtils<Number> collectionUtils = new CollectionUtils<>();
    List<Number>  list = new ArrayList<>();
    //list.add....
    List<Integer>  listTwo = new ArrayList<>();
    //listTwo.add....
    List<Double>  listThree = new ArrayList<>();
    //listThree.add....

    List<Number> list1 = collectionUtils.listCopyTwo(list);
    list1 = collectionUtils.listCopyTwo(listTwo);
    list1 = collectionUtils.listCopyTwo(listThree);
}

当初应用 listCopyTwo 就没有问题,listCopyTwo比照 listCopy 它的适用范围更宽泛也更灵便,listCopy能做的 listCopyTwo 能做,listCopyTwo能做的 listCopy 就不肯定能做了,除此之外,仔细的小伙伴必定发现了,应用上边界通配符的 collection 在函数内只应用到了读操作,遵循了只读不写准则。

看完了上边界通配符,再来看看下边界通配符,仍然是复制办法



/**
 * 儿子
 */
public class Son extends Father{}

/**
 * 父亲
 */
public class Father  extends  Grandpa{}

/**
 * 爷爷
 */
public class Grandpa {}

/**
 * 汇合工具
 */
public class CollectionUtils<T>{

    /**
     * 复制汇合 - 泛型
     * target 指标   src 起源
     */
   public void copy(List<T> target,List<T> src){if (src.size() > target.size()){for (int i = 0; i < src.size(); i++) {target.set(i,src.get(i));
            }
        }
    }
    
}

定义了 3 个类,别离是 Son 儿子、Father父亲、Grandpa爷爷,它们是继承关系,作为汇合元素,还申明了一个 CollectionUtils 类,领有 copy 办法,传入两个汇合,指标汇合与起源汇合,把起源汇合元素复制到指标汇合中,再看看上面这段代码

public static void main(String[] agrs){CollectionUtils<Father> collectionUtils = new CollectionUtils<>();

    List<Father>  fatherTargets = new ArrayList<>();
    List<Father>  fatherSources = new ArrayList<>();
    //fatherSources.add...
    collectionUtils.copy(fatherTargets,fatherSources);
    
    // 子类复制到父类
    List<Son> sonSources = new ArrayList<>();
    //sonSources.add...
    collectionUtils.copy(fatherTargets,sonSources);//err 编译异样
    
}

创立 CollectionUtils 类,泛型的类型参数为 Father 父亲,copy函数入参的泛型填充为 Father,此时copy 只反对泛型为 FatherList,也就说,只反对泛型的类型参数为 Father 之间的复制,如果想反对把子类复制到父类要怎么做,先剖析下 copy 函数,copy函数的入参 src 在函数外部只波及到了 get 函数,即读操作(泛型只作为 get 函数返回类型),合乎只读不写准则,能够采纳上边界通配符,调整代码如下

/**
 * 汇合工具
 */
public class CollectionUtils<T>{

    /**
     * 复制汇合 - 泛型
     * target 指标   src 起源
     */
    public void copy(List<T> target,List<? extends T> src){if (src.size() > target.size()){for (int i = 0; i < src.size(); i++) {target.set(i,src.get(i));
            }
        }
    }
}

public static void main(String[] agrs){CollectionUtils<Father> collectionUtils = new CollectionUtils<>();

    List<Father>  fatherTargets = new ArrayList<>();
    List<Father>  fatherSources = new ArrayList<>();
    //fatherSources.add...
    collectionUtils.copy(fatherTargets,fatherSources);
    
    // 子类复制到父类
    List<Son> sonSources = new ArrayList<>();
    //sonSources.add...
    collectionUtils.copy(fatherTargets,sonSources);
    
    // 把子类复制到父类的父类
    List<Grandpa> grandpaTargets = new ArrayList<>();
    collectionUtils.copy(grandpaTargets,sonSources);//err 编译异样
}

src入参调整为上边界通配符后,copy函数传入 List<Son> sonSources 就没问题了,此时的 copy 函数比相较之前的更加灵便了,反对同类与父子类复制,接着又发现了一个问题,目前能复制到上一级父类,如果是多级父类,还无奈反对,持续剖析 copy 函数,copy函数的入参 target 在函数外部只波及到了 add 函数,即写操作(只作为 add 函数入参),合乎只写不读准则,能够采纳下边界通配符,调整代码如下

/**
 * 汇合工具
 */
public class CollectionUtils<T>{

    /**
     * 复制汇合 - 泛型
     * target 指标   src 起源
     */
    public void copy(List<? super T>  target,List<? extends T> src){if (src.size() > target.size()){for (int i = 0; i < src.size(); i++) {target.set(i,src.get(i));
            }
        }
    }
}

public static void main(String[] agrs){CollectionUtils<Father> collectionUtils = new CollectionUtils<>();

    List<Father>  fatherTargets = new ArrayList<>();
    List<Father>  fatherSources = new ArrayList<>();
    //fatherSources.add...
    collectionUtils.copy(fatherTargets,fatherSources);
    
    // 子类复制到父类
    List<Son> sonSources = new ArrayList<>();
    //sonSources.add...
    collectionUtils.copy(fatherTargets,sonSources);
    
    // 把子类复制到父类的父类
    List<Grandpa> grandpaTargets = new ArrayList<>();
    collectionUtils.copy(grandpaTargets,sonSources);
}

copy函数终于是欠缺了,能够说当初是真正反对父子类复制,不难发现 copy 函数的设计还是遵循通配符准则的,target作为指标汇合,只做写入,合乎只写不读准则,采纳了下边界通配符,src作为起源汇合写入到 target 指标汇合,只做读取,合乎只读不写准则,采纳了上边界通配符,最初设计进去的 copy 函数,它的灵活性与适用范围是远超 <T> 形式设计的。

最初总结一下,什么时候用通配符,如果参数泛型类即要读也要写,那么就不举荐应用,应用失常的泛型即可,如果参数泛型类只读或写,就能够依据准则采纳对应的高低边界,是不是非常简略,最初再说一次读写的含意,这块的确很容易晕

  • 读:所谓读是指参数泛型类,泛型只作为该参数类的函数返回类型,那这个函数就是读,List作为参数泛型类,它的 get 函数就是读
  • 写:所谓写是指参数泛型类,泛型只作为该参数类的函数入参,那这个函数就是写,List作为参数泛型类,它的 add 函数就是读

最初能够举荐下大家能够思考下 StreamforEach函数与 map 函数的设计,在 Java1.8 Stream 中是大量用到了通配符设计

-----------------------------------------------------------------
/**
 * 下边界通配符
 */
void forEach(Consumer<? super T> action);

public interface Consumer<T> {

    // 写办法
    void accept(T t);
}

-----------------------------------------------------------------
/**
 * 高低边界通配符
 */
<R> Stream<R> map(Function<? super T, ? extends R> mapper)

public interface Function<T, R> {

     // 读写办法,T 只作为入参合乎写,R 只作为返回值,合乎读
    R apply(T t);
}
-----------------------------------------------------------------

// 代码案例
public static void main(String[] agrs) {List<Father> fatherList = new ArrayList<>();
        
        Consumer<? super Father> action = new Consumer<Father>() {
            @Override
            public void accept(Father father) {// 执行 father 逻辑}
        };
        
         // 下边界通配符向上转型
        Consumer<? super Father> actionTwo = new Consumer<Grandpa>() {
            @Override
            public void accept(Grandpa grandpa) {// 执行 grandpa 逻辑}
        };
        
         Function<? super Father, ? extends Grandpa> mapper = new Function<Father, Grandpa>() {
            @Override
            public Grandpa apply(Father father) {
                // 执行 father 逻辑后返回 Grandpa
                return new Grandpa();}
        };
        
        // 下边界通配符向上转型,下边界通配符向下转型
         Function<? super Father, ? extends Grandpa> mapperTwo = new Function<Grandpa, Son>() {
            @Override
            public Son apply(Grandpa grandpa) {
                // 执行 grandpa 逻辑后,返回 Son
                return new Son();}
        };
        
        fatherList.stream().forEach(action);
        fatherList.stream().forEach(actionTwo);
        
        fatherList.stream().map(mapper);
        fatherList.stream().map(mapperTwo);
        
    
    }
-----------------------------------------------------------------

有限度泛型场景

有限度泛型很简略了,利用场景就是你须要对泛型的参数类型做限度,就能够应用它,比方上面这段代码

public class GenericClass<T extends Grandpa> {public void test(T t){//....}

}

public static void main(String[] agrs){GenericClass<Grandpa> grandpaGeneric = new GenericClass<>();
    grandpaGeneric.test(new Grandpa());
    grandpaGeneric.test(new Father());
    grandpaGeneric.test(new Son());
    
    GenericClass<Father> fatherGeneric = new GenericClass<>();
    fatherGeneric.test(new Father());
    fatherGeneric.test(new Son());

    GenericClass<Son> sonGeneric = new GenericClass<>();
    sonGeneric.test(new Son());
    
    GenericClass<Object> ObjectGeneric = new GenericClass<>();//err 编译异样}

GenericClass泛型参数化类型被限度为 Grandpa 或其子类,就这么简略,千万不要把有限度泛型与上边界通配符搞混了,这两个不是同一个货色(<T extends Grandpa> != <? extends Grandpa>),<T extends Grandpa>不须要遵循上边界通配符的准则,它就是简略的泛型参数化类型限度,而且没有 super 的写法。

递归泛型场景

在有限度泛型的根底上,又能够衍生出递归泛型,就是本身须要应用到本身,比方汇合进行自定义元素大小比拟的时候,通常会配合 Comparable 接口来实现,看看上面这段代码

public class Person implements Comparable<Person> {

    private int age;

    public Person(int age) {this.age = age;}

    public int getAge() {return age;}

    @Override
    public int compareTo(Person o) {
        // 0 代表相等 1 代表大于  <0 代表小于    
        return this.age - o.age;
    }
}


/**
 * 汇合工具
 */
public class CollectionUtils{
    
    /**
     * 获取汇合最大值
     */
    public static  <E extends Comparable<E>> E max(List<E> list){
        E result = null;
        for (E e : list) {if (result == null || e.compareTo(result) > 0){result = e;}
        }
        return result;
    }
}


public static void main(String[] agrs){List<Person> personList = new ArrayList<>();
    personList.add(new Person(12));
    personList.add(new Person(19));
    personList.add(new Person(20));
    personList.add(new Person(5));
    personList.add(new Person(18));
    // 返回年龄最大的 Person 元素 
    Person max = CollectionUtils.max(personList);

}

重点关注 max 泛型函数,max泛型函数的指标是返回汇合最大的元素,外部比拟元素大小,取最大值返回,也就说须要和同类型元素做比拟,<E extends Comparable<E>>含意是,泛型 E 必须是 Comparable 或其子类 / 实现类,因为比拟元素是同类型,所以 Comparable 泛型也是 E, 最终接管的List 泛型参数化类型必须实现了 Comparable 接口,并且 Comparable 接口填充的泛型也是该参数化类型,就像上述代码一样。

对于我

这里是阿星,一个酷爱技术的 Java 程序猿,在公众号 「程序猿阿星」 里将会定期分享操作系统、计算机网络、Java、分布式、数据库等精品原创文章,2021,与您在 Be Better 的路上独特成长!。

非常感谢各位人才能 看到这里,原创不易,文章有帮忙能够「点个赞」或「分享与评论」,都是反对(莫要白嫖)!

愿你我都能奔赴在各自想去的路上,咱们下篇文章见!

正文完
 0