从零开始来看一下Java泛型的设计

引言

泛型是Java中一个非常重要的知识点,在Java集合类框架中泛型被广泛应用。本文我们将从零开始来看一下Java泛型的设计,将会涉及到通配符处理,以及让人苦恼的类型擦除。

泛型基础

泛型类

我们首先定义一个简单的Box类:

public class Box {private String object;public void set(String object) { this.object = object; }public String get() { return object; }
}

这是最常见的做法,这样做的一个坏处是Box里面现在只能装入String类型的元素,今后如果我们需要装入Integer等其他类型的元素,还必须要另外重写一个Box,代码得不到复用,使用泛型可以很好的解决这个问题。

public class Box<T> {// T stands for "Type"private T t;public void set(T t) { this.t = t; }public T get() { return t; }
}

这样我们的Box类便可以得到复用,我们可以将T替换成任何我们想要的类型:

Box<Integer> integerBox = new Box<Integer>();
Box<Double> doubleBox = new Box<Double>();
Box<String> stringBox = new Box<String>();

泛型方法

看完了泛型类,接下来我们来了解一下泛型方法。声明一个泛型方法很简单,只要在返回类型前面加上一个类似<K, V>的形式就行了:

public class Util {public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {return p1.getKey().equals(p2.getKey()) &&p1.getValue().equals(p2.getValue());}
}
public class Pair<K, V> {private K key;private V value;public Pair(K key, V value) {this.key = key;this.value = value;}public void setKey(K key) { this.key = key; }public void setValue(V value) { this.value = value; }public K getKey()   { return key; }public V getValue() { return value; }
}

我们可以像下面这样去调用泛型方法:

Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.<Integer, String>compare(p1, p2);

或者在Java1.7/1.8利用type inference,让Java自动推导出相应的类型参数:

Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.compare(p1, p2);

边界符

现在我们要实现这样一个功能,查找一个泛型数组中大于某个特定元素的个数,我们可以这样实现:

public static <T> int countGreaterThan(T[] anArray, T elem) {int count = 0;for (T e : anArray)if (e > elem)  // compiler error++count;return count;
}

但是这样很明显是错误的,因为除了short, int, double, long, float, byte, char等原始类型,其他的类并不一定能使用操作符>,所以编译器报错,那怎么解决这个问题呢?答案是使用边界符。

public interface Comparable<T> {public int compareTo(T o);
}

做一个类似于下面这样的声明,这样就等于告诉编译器类型参数T代表的都是实现了Comparable接口的类,这样等于告诉编译器它们都至少实现了compareTo方法。

public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {int count = 0;for (T e : anArray)if (e.compareTo(elem) > 0)++count;return count;
}

通配符

在了解通配符之前,我们首先必须要澄清一个概念,还是借用我们上面定义的Box类,假设我们添加一个这样的方法:

public void boxTest(Box<Number> n) { /* ... */ }

那么现在Box<Number> n允许接受什么类型的参数?我们是否能够传入Box<Integer>或者Box<Double>呢?答案是否定的,虽然Integer和Double是Number的子类,但是在泛型中Box<Integer>或者Box<Double>Box<Number>之间并没有任何的关系。这一点非常重要,接下来我们通过一个完整的例子来加深一下理解。

首先我们先定义几个简单的类,下面我们将用到它:

class Fruit {}
class Apple extends Fruit {}
class Orange extends Fruit {}

下面这个例子中,我们创建了一个泛型类Reader,然后在f1()中当我们尝试Fruit f = fruitReader.readExact(apples);编译器会报错,因为List<Fruit>List<Apple>之间并没有任何的关系。

public class GenericReading {static List<Apple> apples = Arrays.asList(new Apple());static List<Fruit> fruit = Arrays.asList(new Fruit());static class Reader<T> {T readExact(List<T> list) {return list.get(0);}}static void f1() {Reader<Fruit> fruitReader = new Reader<Fruit>();// Errors: List<Fruit> cannot be applied to List<Apple>.// Fruit f = fruitReader.readExact(apples);}public static void main(String[] args) {f1();}
}

但是按照我们通常的思维习惯,Apple和Fruit之间肯定是存在联系,然而编译器却无法识别,那怎么在泛型代码中解决这个问题呢?我们可以通过使用通配符来解决这个问题:

static class CovariantReader<T> {T readCovariant(List<? extends T> list) {return list.get(0);}
}
static void f2() {CovariantReader<Fruit> fruitReader = new CovariantReader<Fruit>();Fruit f = fruitReader.readCovariant(fruit);Fruit a = fruitReader.readCovariant(apples);
}
public static void main(String[] args) {f2();
}

这样就相当与告诉编译器, fruitReader的readCovariant方法接受的参数只要是满足Fruit的子类就行(包括Fruit自身),这样子类和父类之间的关系也就关联上了。

PECS原则

上面我们看到了类似<? extends T>的用法,利用它我们可以从list里面get元素,那么我们可不可以往list里面add元素呢?我们来尝试一下:

public class GenericsAndCovariance {public static void main(String[] args) {// Wildcards allow covariance:List<? extends Fruit> flist = new ArrayList<Apple>();// Compile Error: can't add any type of object:// flist.add(new Apple())// flist.add(new Orange())// flist.add(new Fruit())// flist.add(new Object())flist.add(null); // Legal but uninteresting// We Know that it returns at least Fruit:Fruit f = flist.get(0);}
}

答案是否定,Java编译器不允许我们这样做,为什么呢?对于这个问题我们不妨从编译器的角度去考虑。因为List<? extends Fruit> flist它自身可以有多种含义:

List<? extends Fruit> flist = new ArrayList<Fruit>();
List<? extends Fruit> flist = new ArrayList<Apple>();
List<? extends Fruit> flist = new ArrayList<Orange>();
  • 当我们尝试add一个Apple的时候,flist可能指向new ArrayList<Orange>();
  • 当我们尝试add一个Orange的时候,flist可能指向new ArrayList<Apple>();
  • 当我们尝试add一个Fruit的时候,这个Fruit可以是任何类型的Fruit,而flist可能只想某种特定类型的Fruit,编译器无法识别所以会报错。

所以对于实现了<? extends T>的集合类只能将它视为Producer向外提供(get)元素,而不能作为Consumer来对外获取(add)元素。

如果我们要add元素应该怎么做呢?可以使用<? super T>

public class GenericWriting {static List<Apple> apples = new ArrayList<Apple>();static List<Fruit> fruit = new ArrayList<Fruit>();static <T> void writeExact(List<T> list, T item) {list.add(item);}static void f1() {writeExact(apples, new Apple());writeExact(fruit, new Apple());}static <T> void writeWithWildcard(List<? super T> list, T item) {list.add(item)}static void f2() {writeWithWildcard(apples, new Apple());writeWithWildcard(fruit, new Apple());}public static void main(String[] args) {f1(); f2();}
}

这样我们可以往容器里面添加元素了,但是使用super的坏处是以后不能get容器里面的元素了,原因很简单,我们继续从编译器的角度考虑这个问题,对于List<? super Apple> list,它可以有下面几种含义:

List<? super Apple> list = new ArrayList<Apple>();
List<? super Apple> list = new ArrayList<Fruit>();
List<? super Apple> list = new ArrayList<Object>();

当我们尝试通过list来get一个Apple的时候,可能会get得到一个Fruit,这个Fruit可以是Orange等其他类型的Fruit。

根据上面的例子,我们可以总结出一条规律,”Producer Extends, Consumer Super”:

  • “Producer Extends” – 如果你需要一个只读List,用它来produce T,那么使用? extends T
  • “Consumer Super” – 如果你需要一个只写List,用它来consume T,那么使用? super T
  • 如果需要同时读取以及写入,那么我们就不能使用通配符了。

如何阅读过一些Java集合类的源码,可以发现通常我们会将两者结合起来一起用,比如像下面这样:

public class Collections {public static <T> void copy(List<? super T> dest, List<? extends T> src) {for (int i=0; i<src.size(); i++)dest.set(i, src.get(i));}
}

类型擦除

Java泛型中最令人苦恼的地方或许就是类型擦除了,特别是对于有C++经验的程序员。类型擦除就是说Java泛型只能用于在编译期间的静态类型检查,然后编译器生成的代码会擦除相应的类型信息,这样到了运行期间实际上JVM根本就知道泛型所代表的具体类型。这样做的目的是因为Java泛型是1.5之后才被引入的,为了保持向下的兼容性,所以只能做类型擦除来兼容以前的非泛型代码。对于这一点,如果阅读Java集合框架的源码,可以发现有些类其实并不支持泛型。

说了这么多,那么泛型擦除到底是什么意思呢?我们先来看一下下面这个简单的例子:

public class Node<T> {private T data;private Node<T> next;public Node(T data, Node<T> next) }         this.data = data;this.next = next;}public T getData() { return data; }// ...
}

编译器做完相应的类型检查之后,实际上到了运行期间上面这段代码实际上将转换成:

public class Node {private Object data;private Node next;public Node(Object data, Node next) {this.data = data;this.next = next;}public Object getData() { return data; }// ...
}

这意味着不管我们声明Node<String>还是Node<Integer>,到了运行期间,JVM统统视为Node<Object>。有没有什么办法可以解决这个问题呢?这就需要我们自己重新设置bounds了,将上面的代码修改成下面这样:

public class Node<T extends Comparable<T>> {private T data;private Node<T> next;public Node(T data, Node<T> next) {this.data = data;this.next = next;}public T getData() { return data; }// ...
}

这样编译器就会将T出现的地方替换成Comparable而不再是默认的Object了:

public class Node {private Comparable data;private Node next;public Node(Comparable data, Node next) {this.data = data;this.next = next;}public Comparable getData() { return data; }// ...
}

上面的概念或许还是比较好理解,但其实泛型擦除带来的问题远远不止这些,接下来我们系统地来看一下类型擦除所带来的一些问题,有些问题在C++的泛型中可能不会遇见,但是在Java中却需要格外小心。

问题一

在Java中不允许创建泛型数组,类似下面这样的做法编译器会报错:

List<Integer>[] arrayOfLists = new List<Integer>[2];  // compile-time error

为什么编译器不支持上面这样的做法呢?继续使用逆向思维,我们站在编译器的角度来考虑这个问题。

我们先来看一下下面这个例子:

Object[] strings = new String[2];
strings[0] = "hi";   // OK
strings[1] = 100;    // An ArrayStoreException is thrown.

对于上面这段代码还是很好理解,字符串数组不能存放整型元素,而且这样的错误往往要等到代码运行的时候才能发现,编译器是无法识别的。接下来我们再来看一下假设Java支持泛型数组的创建会出现什么后果:

Object[] stringLists = new List<String>[];  // compiler error, but pretend it's allowed
stringLists[0] = new ArrayList<String>();   // OK
// An ArrayStoreException should be thrown, but the runtime can't detect it.
stringLists[1] = new ArrayList<Integer>();

假设我们支持泛型数组的创建,由于运行时期类型信息已经被擦除,JVM实际上根本就不知道new ArrayList<String>()new ArrayList<Integer>()的区别。类似这样的错误假如出现才实际的应用场景中,将非常难以察觉。

如果你对上面这一点还抱有怀疑的话,可以尝试运行下面这段代码:

public class ErasedTypeEquivalence {public static void main(String[] args) {Class c1 = new ArrayList<String>().getClass();Class c2 = new ArrayList<Integer>().getClass();System.out.println(c1 == c2); // true}
}

问题二

继续复用我们上面的Node的类,对于泛型代码,Java编译器实际上还会偷偷帮我们实现一个Bridge method。

public class Node<T> {public T data;public Node(T data) { this.data = data; }public void setData(T data) {System.out.println("Node.setData");this.data = data;}
}
public class MyNode extends Node<Integer> {public MyNode(Integer data) { super(data); }public void setData(Integer data) {System.out.println("MyNode.setData");super.setData(data);}
}

看完上面的分析之后,你可能会认为在类型擦除后,编译器会将Node和MyNode变成下面这样:

public class Node {public Object data;public Node(Object data) { this.data = data; }public void setData(Object data) {System.out.println("Node.setData");this.data = data;}
}
public class MyNode extends Node {public MyNode(Integer data) { super(data); }public void setData(Integer data) {System.out.println("MyNode.setData");super.setData(data);}
}

实际上不是这样的,我们先来看一下下面这段代码,这段代码运行的时候会抛出ClassCastException异常,提示String无法转换成Integer:

MyNode mn = new MyNode(5);
Node n = mn; // A raw type - compiler throws an unchecked warning
n.setData("Hello"); // Causes a ClassCastException to be thrown.
// Integer x = mn.data;

如果按照我们上面生成的代码,运行到第3行的时候不应该报错(注意我注释掉了第4行),因为MyNode中不存在setData(String data)方法,所以只能调用父类Node的setData(Object data)方法,既然这样上面的第3行代码不应该报错,因为String当然可以转换成Object了,那ClassCastException到底是怎么抛出的?

实际上Java编译器对上面代码自动还做了一个处理:

class MyNode extends Node {// Bridge method generated by the compilerpublic void setData(Object data) {setData((Integer) data);}public void setData(Integer data) {System.out.println("MyNode.setData");super.setData(data);}// ...
}

这也就是为什么上面会报错的原因了,setData((Integer) data);的时候String无法转换成Integer。所以上面第2行编译器提示unchecked warning的时候,我们不能选择忽略,不然要等到运行期间才能发现异常。如果我们一开始加上Node<Integer> n = mn就好了,这样编译器就可以提前帮我们发现错误。

问题三

正如我们上面提到的,Java泛型很大程度上只能提供静态类型检查,然后类型的信息就会被擦除,所以像下面这样利用类型参数创建实例的做法编译器不会通过:

public static <E> void append(List<E> list) {E elem = new E();  // compile-time errorlist.add(elem);
}

但是如果某些场景我们想要需要利用类型参数创建实例,我们应该怎么做呢?可以利用反射解决这个问题:

public static <E> void append(List<E> list, Class<E> cls) throws Exception {E elem = cls.newInstance();   // OKlist.add(elem);
}

我们可以像下面这样调用:

List<String> ls = new ArrayList<>();
append(ls, String.class);

实际上对于上面这个问题,还可以采用Factory和Template两种设计模式解决,感兴趣的朋友不妨去看一下Thinking in Java中第15章中关于Creating instance of types(英文版第664页)的讲解,这里我们就不深入了。

问题四

我们无法对泛型代码直接使用instanceof关键字,因为Java编译器在生成代码的时候会擦除所有相关泛型的类型信息,正如我们上面验证过的JVM在运行时期无法识别出ArrayList<Integer>ArrayList<String>的之间的区别:

public static <E> void rtti(List<E> list) {if (list instanceof ArrayList<Integer>) {  // compile-time error// ...}
}
=> { ArrayList<Integer>, ArrayList<String>, LinkedList<Character>, ... }

和上面一样,我们可以使用通配符重新设置bounds来解决这个问题:

public static void rtti(List<?> list) {if (list instanceof ArrayList<?>) {  // OK; instanceof requires a reifiable type// ...}
}



作者:ziwenxie

来源:51CTO

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/288798.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php json error,PHP 7.3 中的 JSON 错误处理

PHP 7.3 为 json_encode() 和 json_decode() 函数增加的一个新特性使其更好的处理错误。这个特性「 RFC 」以 23 比 0 的投票结果被一致接受。让我们看一看在 PHP 7.2 及一下版本中是如何处理 JSON 错误的&#xff0c;以及 PHP 7.3 中新的改进。背景当前在 PHP7.2 版本中&#…

【C语言简单说】十九:二维数组循环嵌套(2)

这节直接用循环嵌套来输出二维数组了&#xff1a; 注&#xff1a;我说的队和列并不是一般说法&#xff0c;我用此比喻好让新手更好理解。 #include<stdio.h> #include<stdlib.h> int main() {int array[2][3]{1,2,3,4,5,6};//第一句 int i,j;//第二句 for(i0;i&l…

lia人是什么意思_狗狗喜欢舔人到底什么意思?毛孩的心思主人你要懂

很多人都喜欢养狗&#xff0c;因为它们忠诚、淘气、可爱。同时&#xff0c;狗狗也有很多奇怪的习惯&#xff0c;例如&#xff1a;喜欢舔人&#xff0c;喜欢追逐活动的东西等等。不过大多数狗主人通常都会有一个最想知道的问题&#xff1a;为什么狗狗总喜欢舔人&#xff0c;它们…

“爱思助手”曝为iOS木马:可绕过苹果DRM机制

一款新的iOS木马已在国内曝光&#xff0c;它可以通过PC感染未越狱的iOS设备&#xff0c;而无需利用企业证书。Palo Alto Networks指出&#xff0c;其名叫“爱思助手”(AceDeceiver)&#xff0c;目前正在影响我国的iOS用户。“爱思助手”利用了苹果数字版权管理(DRM)上的FairPla…

php运行条件,PHP配置环境要求 php运行的先决条件

类型&#xff1a;编程相关大小&#xff1a;320KB语言&#xff1a;中文 评分&#xff1a;6.6标签&#xff1a;立即下载在本教程中&#xff0c;假设用户的服务器已经安装并运行了 PHP&#xff0c;所有以 .php 结尾的文件都将由 PHP 来处理。在大部分的服务器上&#xff0c;这是 P…

【C语言简单说】二十:指针基础

。。据说指针很难 其实稍微理解概念不难。 先看百科的定义&#xff1a;在计算机科学中&#xff0c;指针&#xff08;Pointer&#xff09;是编程语言中的一个对象&#xff0c;利用地址&#xff0c;它的值直接指向&#xff08;points to&#xff09;存在电脑存储器中另一个地方的…

Javascript中的循环变量声明,到底应该放在哪儿?

不放走任何一个细节。相信很多Javascript开发者都在声明循环变量时犹 豫过var i到底应该放在哪里&#xff1a;放在不同的位置会对程序的运行产生怎样的影响&#xff1f;哪一种方式符合Javascript的语言规范&#xff1f;哪一种方式和ecma标准未来的发展 方向匹配&#xff1f;本文…

Delphi全局热键的注册

1.在窗启动时创建ATOM;(aatom:ATOM;定义在private中&#xff09; 1 if FindAtom(ZWXhotKey)0 then 2 begin 3 aatom:GlobalAddAtom(ZWXhotKey); 4 end; 5 if RegisterHotKey(Handle,aatom,MOD_ALT,$41) then 6 begin 7 MessageBox(Handle,按alta,提示,MB_OK); 8 end; 2.定义处…

【C语言简单说】二十一:双重指针基础 (完结)

其实后面这两节我是用我几年前写的教程复制过来的。。。 ’ – ’ ) ( &#xff13; )╱~~ 如有错误&#xff0c;请留言提醒哈~~~尴尬的笑。 多重指针呢其实就是指向指针的指针。 首先&#xff0c;变量大家都知道是啥意思了吧&#xff1f;一个变量是有地址的。那么指针变量也是…

精彩回顾|「源」来如此 第六期 - 开源经济与产业投资

| 作者&#xff1a;活动组、袁睿斌| 编辑&#xff1a;金心悦| 设计&#xff1a;朱亿钦4月17日 14:00&#xff0c;由开源社联合云启资本、易观分析、云赛空间&#xff0c;以及微软 Reactor 共同主办&#xff0c;由示说网提供转播支持的「源」来如此 第六期直播活动如约而至。在本…

C#趣味程序---真分数序列

问题&#xff1a;按递增顺序依次列出所有分母为40&#xff0c;分子小于40的最简真分数。 分析&#xff1a;利用最大公约数 using System;namespace ConsoleApplication1 {class Program{static void Main(string[] args){for(int i1;i<40;i){int a 40;int b i;while (b!0…

有关 php __autoload 自动加载类函数的用法

这个函数是一个自动加载类函数&#xff0c;啥事自动加载函数&#xff0c;顾名思义 &#xff0c;那就是自己就会加载类的函数&#xff08;原谅我废话了&#xff09; 我们先看下面的代码&#xff1a; <?php function __autoload($classname) {echo "helloworld";…

IP签名档PHP源码,IPCard 一款天气图标签名档源码

源码介绍本源码对接高德z地图开发者平台的API实现获取IP和天气数据并使用php将天气的图标与文字相结合&#xff0c;形成一张IP签名档图片&#xff0c;最后呈现出来使用说明首先去高德开放平台申请KEY&#xff0c;点击右上角的注册按钮并登录账号&#xff0c;进入控制台&#xf…

Fiddler之如何通过浏览器输入链接地址修改页面返回数据的内容

1 问题 比如我们在浏览器里面输入www.baidu.com,那么就正常返回页面,我们怎么修改这个页面的返回内容呢?我们可以功过Fiddler构来实现,比如我们现在要实现在浏览器里面输入www.baidu.com,然后返回的页面返回chenyu这个功能。 2 操作过程 1) 由于我的谷歌浏览器使用了Swi…

大数据对六大领域的挑战

第一个挑战是大数据对人性假设的挑战。 管理学自诞生开始&#xff0c;就以人为对象&#xff0c;以人性假设为前提不断演化出各种理论。第一个提出科学管理理论的泰勒假设人是“经济人”&#xff0c;后来梅奥假设人是“社会人”&#xff0c;西蒙则构造了“决策人假设”。自西蒙之…

CentOS 6.3(x86_64)下安装Oracle 10g R2

CentOS 6.3(x86_64)下安装Oracle 10g R2 目 录 一、硬件要求 二、软件 三、系统安装注意 四、安装Oracle前的系统准备工作 五、安装Oracle&#xff0c;并进行相关设置 六、升级Oracle到patchset 10.2.0.4 七、使用rlwrap调用sqlplus中历史命令 一、硬件要求 1、内存 & swap…

比__autoload 更灵活的 spl_autoload_register 用法

直接上代码了&#xff1a; <?php function loadclass( $class ) { $file $class . .php; if (is_file($file)) { require_once($file); } } spl_autoload_register( loadclass ); $obj new Test1(); $obj->TestFunction(); ?> 以上php代码有一个函数loadclass有…

php短信接口怎么用,php短信接口接入详细过程

短信接口被广泛应用于互联网产品&#xff0c;在开发网站或app等应用时会经常遇到接入短信接口的需求&#xff0c;接入短信接口详细过程如下&#xff1a;首先需要找到一家短信接口服务商&#xff0c;获取短信接口调用地址和相关接入参考文档&#xff0c;这里就以动力思维乐信短信…

存储世界瞬息万变 SSD掀行业浪潮

存储世界瞬息万变&#xff0c;数据创建和共享速度也确实惊人。近几年&#xff0c;企业级存储市场群雄逐鹿&#xff0c;烽烟四起。SSD厂商迅速崛起&#xff0c;大杀四方。其性能、可靠性和容量秒杀“前任”HDD&#xff0c;尤其是惊人的速度更是受到用户追捧。 在虚拟化、云计算、…

numpy拼接_巧用numpy切分图片

昨晚发了接受投稿文章&#xff0c;昨晚就有读者积极来文章啦&#xff0c;几轮邮件交流了修改意见后&#xff0c;今天就发布啦&#xff0c;这篇的稿费是300。之前无聊在刷视频的时候看到这么一个有意思的视频&#xff08;现在视频找不到&#xff0c;忘记关键字了 &#xff09;&a…