Java Generics and Collections-8.1
8.1 Take Care when Calling Legacy Code
通常,泛型都是在编译时检查的,而不是运行时。便意识检查可以提早通知错误,而不至于到运行时才出问题。
但有时后编译时检查不一定就坚不可摧,因为有时我们在运行时才能之道具体类型。
(唉,翻译水平有限,还是看代码吧)
package java_generics_collections.chap08;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jintaox on 2016/3/21.
*/
public class LegacyLibrary {
public static void addItems(List list) {
list.add(new Integer(1));
list.add("two");
}
public static List getItems() {
List list = new ArrayList();
list.add(new Integer(3));
list.add("four");
return list;
}
}
使用这段代码的客户端被告知item永远是整数。
package java_generics_collections.chap08;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jintaox on 2016/3/21.
*/
public class NaiveClient {
public static void processItems() {
List<Integer> list = new ArrayList<>();
LegacyLibrary.addItems(list);
List<Integer> list2 = LegacyLibrary.getItems();//unchecked warnings
//sometime later可能过了很久才打算使用list中的数据
int s = 0;
for (int i : list) {
s += i;//class cast exception
}
for (int i : list2) {
s += i;//class cast exception
}
}
@Test
public void test_processItems() throws Exception {
processItems();
}
}
当我们对这段代码跑测试的时候,异常如下:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java_generics_collections.chap08.NaiveClient.processItems(NaiveClient.java:18)
at java_generics_collections.chap08.NaiveClient.test_processItems(NaiveClient.java:28)
...
也就是说我们从集合中拿出数据并把它当作`Integer`来用的时候,它抛出了异常,也就是说错误定位我们只能快速到达这里,但究其原因是因为我们在插入的时候,插入了一个`String`类型,
而我们很难定位到这里,只能从头开始读代码。
来看另一个客户端(以下代码是可以通过编译检查)
package java_generics_collections.chap08;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by jintaox on 2016/3/21.
*/
public class WaryClient {
public static void processItems() {
List<Integer> list = new ArrayList<>();
List<Integer> view = Collections.checkedList(list, Integer.class);
LegacyLibrary.addItems(view);
List<Integer> list2 = LegacyLibrary.getItems();//unchecked
for (int i : list2) {
//class case exception
System.out.println(i);
}
}
@Test
public void test_processItems() throws Exception {
processItems();
}
}
在这个客户端里面,我们使用了工具类`Collections`中的`checkedList`方法,还是先看运行结果吧
java.lang.ClassCastException: Attempt to insert class java.lang.String element into collection with element type class java.lang.Integer
at java.util.Collections$CheckedCollection.typeCheck(Collections.java:3037)
at java.util.Collections$CheckedCollection.add(Collections.java:3080)
at java_generics_collections.chap08.LegacyLibrary.addItems(LegacyLibrary.java:12)
at java_generics_collections.chap08.WaryClient.processItems(WaryClient.java:16)
at java_generics_collections.chap08.WaryClient.test_processItems(WaryClient.java:27)
看,我们一下就定位到了插入的地方,这样就大大加快我们定位错误的速度。
`checkedList`方法的api介绍: Returns a dynamically typesafe view of the specified collection.
checkedList源码分析待定
加油,我要做Java专家。
Java Generics and Collections-8.1的更多相关文章
- python 中的sort 和java中的Collections.sort()函数的使用
x=[1,2,3] x.sort()对的,x这个都变了 y=x.sort()错误 y=sorted(x)对的,x拍好序的一个副本 python中用匿名函数和自定义函数排序:(很奇怪的是比较函数返回的是 ...
- Java Concurrency - Concurrent Collections
Data structures are a basic element in programming. Almost every program uses one or more types of d ...
- thinking in java Generics Latent typing
The beginning of this chapter introduced the idea of writing code that can be applied as generally a ...
- Thinking in java——Generics
Ordinary classes and methods work with specific types: either primitives or class types. If you are ...
- 【Java】Java中的Collections类——Java中升级版的数据结构【转】
一般来说课本上的数据结构包括数组.单链表.堆栈.树.图.我这里所指的数据结构,是一个怎么表示一个对象的问题,有时候,单单一个变量声明不堪大用,比如int,String,double甚至一维数组.二维数 ...
- Java中的Collections类
转载:https://blog.csdn.net/yangxingpa/article/details/80515963 从[Java]Java中的Collections类——Java中升级版的数据结 ...
- Java Generics and Collections-2.3
2.3 Wildcards with super 这里就直接拿书上的例子好了,这是Collections里面的一个方法: public static <T> void copy(List& ...
- java List 排序 Collections.sort() 对 List 排序
class User { String name; String age; public User(String name,String age){ this.name=name; this.a ...
- 黑马程序员——JAVA基础之Collections和Arrays,数组集合的转换
------- android培训.java培训.期待与您交流! ---------- 集合框架的工具类: Collections : 集合框架的工具类.里面定义的都是静态方法. Col ...
随机推荐
- Facebook Paper使用的第三方库
Facebook Paper使用的第三方库 第三方库名 简介 链接 ACE code editor https://github.com/ajaxorg/ace Appirater 用户评分组件 ht ...
- MyEclipse 2014 GA 和 MyEclipse 2015 CI 和 Eclipse Luna 最新最全下载地址
官方下载地址: Eclipse 标准版 x86 http://mirror.hust.edu.cn/eclipse//technology/epp/downloads/release/luna/R/e ...
- html的留言板制作(js)
这次留言板运用到了最基础的localstorage的本地存储,展现的效果主要有: 1.编写留言2.留言前可以编辑自己的留言昵称.不足之处: 1.未能做出我喜欢的类似于网易的叠楼功能. 2.未能显示评论 ...
- WPF筛选、排序和分组
可以通过CollectionViewSource或者CollectionView对视图进行排序.筛选和分组. 一.通过CollectionViewSource listingDataView是Coll ...
- SharePoint中新创建的Web Application在浏览器中报404错误
问题描述:在安装完成SharePoint 2010后,进入Central Administration,创建一个新的Web Application,可以正常创建,但访问时却返回404. 平台环境:Wi ...
- 从零开始学Python第六周:面向对象基础(需修改)
标签(空格分隔): 面向对象 一,面向对象基础 (1)面向对象概述 面向过程:根据业务逻辑从上到下写代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 面向对象:对函数进行分类 ...
- Mybatis中javaType和jdbcType对应关系
JDBC Type Java Type CHAR String VARCHAR String LONGVARCHAR ...
- 设计模式学习之路——Decorator装饰模式(结构模式)
子类复子类,子类何其多 假如我们需要为游戏中开发一种坦克,除了各种不同型号的坦克外,我们还希望在不同场合中为其增加以下一种或多种功能:比如红外线夜视功能,比如水陆两栖功能,比如卫星定位功能等等. 动机 ...
- Linux(Centos)之安装Redis及注意事项
1.redis简单说明 a.在前面我简单的说过redis封装成共用类的实现,地址如下:http://www.cnblogs.com/hanyinglong/p/Redis.html. b.redis是 ...
- windows如何远程桌面mac
mac远程windows系统比较容易,但是windows远程mac就相对复杂一点,需要借助第三方工具来实现. 下面给出简要的远程步骤: 1.登录mac,点击苹果图标,然后单击[系统偏好设置...].如 ...