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的更多相关文章

  1. python 中的sort 和java中的Collections.sort()函数的使用

    x=[1,2,3] x.sort()对的,x这个都变了 y=x.sort()错误 y=sorted(x)对的,x拍好序的一个副本 python中用匿名函数和自定义函数排序:(很奇怪的是比较函数返回的是 ...

  2. Java Concurrency - Concurrent Collections

    Data structures are a basic element in programming. Almost every program uses one or more types of d ...

  3. thinking in java Generics Latent typing

    The beginning of this chapter introduced the idea of writing code that can be applied as generally a ...

  4. Thinking in java——Generics

    ​Ordinary classes and methods work with specific types: either primitives or class types. If you are ...

  5. 【Java】Java中的Collections类——Java中升级版的数据结构【转】

    一般来说课本上的数据结构包括数组.单链表.堆栈.树.图.我这里所指的数据结构,是一个怎么表示一个对象的问题,有时候,单单一个变量声明不堪大用,比如int,String,double甚至一维数组.二维数 ...

  6. Java中的Collections类

    转载:https://blog.csdn.net/yangxingpa/article/details/80515963 从[Java]Java中的Collections类——Java中升级版的数据结 ...

  7. Java Generics and Collections-2.3

    2.3 Wildcards with super 这里就直接拿书上的例子好了,这是Collections里面的一个方法: public static <T> void copy(List& ...

  8. java List 排序 Collections.sort() 对 List 排序

    class User { String name; String age;  public User(String name,String age){  this.name=name;  this.a ...

  9. 黑马程序员——JAVA基础之Collections和Arrays,数组集合的转换

    ------- android培训.java培训.期待与您交流! ---------- 集合框架的工具类:        Collections : 集合框架的工具类.里面定义的都是静态方法. Col ...

随机推荐

  1. 怎样使用My97日期控件

    有网友说无法使用My97日期控件,Insus.NET测试一下,是可以正常使用了. 在ASP.NET MVC环境中测试. 去官网下载My97日期控件程序包: 下载解压之后,把程序的目录拷贝至projec ...

  2. C# decimal保留指定的小数位数,不四舍五入

    decimal保留指定位数小数的时候,.NET自带的方法都是四舍五入的. 项目中遇到分摊金额的情况,最后一条的金额=总金额-已经分摊金额的和. 这样可能导致最后一条分摊的时候是负数,所以自己写了一个保 ...

  3. SQL SERVER2012附加 (PS:开始试过sql2012直接附加失败)

    Northwind 示例数据库下载:  NORTHWND.MDF   (PS:开始试过sql2012直接附加失败) 新建查询-执行下面代码 USE [master] GO CREATE DATABAS ...

  4. python基础之数据类型(二)

    Python3 元组 Python 的元组与列表类似,不同之处在于元组的元素不能修改. 元组使用小括号,列表使用方括号. 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可. 不可变的tupl ...

  5. 七牛--关于图片上传方向不统一的问题--主要关于图片EXIF信息中旋转参数Orientation的理解

    [图片引用方向纠正]直接在图片后面添加 ?imageMogr/auto-orient eg:http://data.upfitapp.com/data/2016/10/18/1629114767606 ...

  6. c#的那些有效性判断

    在开发中合理的对象有效性判断是程序健壮性的重要保障,也有利于提高程序的执行效率.本人简单总结了几个需要判断对象是否为空的例子,分享如下: 一.集合对象中可以包含空对象,遍历集合对象时要同时判断集合中的 ...

  7. Objective-C 排序

    在Objective-C中,排序分为: 1.Foundation框架中的对象排序 2.自定义对象排序 例子:每个学生都有一个成绩score属性,根据成绩score对学生排序 自定义对象 Student ...

  8. Sharepoint学习笔记—习题系列--70-576习题解析 -(Q128-Q130)

    Question  128 You are designing a SharePoint 2010 solution that includes a custom site definition an ...

  9. SDWebImage原理及使用(转)

    转自http://www.cnblogs.com/jys509/p/5199997.html SDWebImage托管在github上.https://github.com/rs/SDWebImage ...

  10. IOS Emoji表情

    IOS Emoji 前言:我比较喜欢有趣的东西,有一些有趣的小东西,可能不是多么多么牛逼,也可能不需要多高深的技巧,也不会为其他什么强大的功能而服务,但是有时候将很多有趣的小东西组合起来运用,比如在你 ...