【双语】不为人知的集合异常检查工具:Collections.checkedCollection()

本贴最后更新于 2634 天前,其中的信息可能已经东海扬尘

英文原文链接:https://www.javaspecialists.eu/archive/Issue251.htm

摘要: Java 在 5.0 的时候已经具备了检查集合中的元素类型是否正确的能力,但是只有很少一部分程序员知道这个功能,这个功能在代码调试阶段起到了非常巨大的作用,它可以在早期就把异常抛出。

Dinosaurs roamed the earth. Fred Flintstone wrote Applets with JBuilder. A shaft of lightning split the dark sky and with a flash <> appeared on his amber screen. Fred scratched his head. _"What on flat earth was List<String>?"

在那古老的恐龙时代,原始人弗莱德正在用 Jbuilder 写一个 Applets 程序,一道闪电劈开了昏暗的天空,<> 在弗莱德那琥珀显示器上不停的闪烁。弗莱德抓了抓脑袋说道:“List<String> 是个什么鬼?”

It was the advent of generics.

这就是泛型的降临

Programmers do not like change. Or rather, we do not like change that will break something that was working perfectly well before. Java 1.4 introduced the **assert** keyword. It broke a bunch of our classes. Java 1.5 added **enum** to the relatively short list of reserved words, a popular name for Enumeration instances. And that was the last time a new keyword was added to the Java Programming Language. Sun Microsystems' engineers knew their audience. They also knew that for their generics to be accepted, old code should preferably still compile without any changes necessary.

程序员不喜欢变化,不如说我们不喜欢去接受一些新的改变我们编程方式的东西,因为我们之前的编程方式已经做的很熟练和完美了。Java1.4 加入了“断言” assert 关键字,他改变了我们大量的 java 类,Java1.5 添加了枚举 enum (Enumeration instances)这个流行的关键字,这也是最后一次向 Java 中添加关键字了。Sun 公司(java 的创始公司已被 Oracle 收购)的工程师了解他们的用户,并很肯定他们的用户也能接受泛型,因为使用泛型你不需要修改之前的任何代码。

Generics were designed so we could ignore them if we wanted to. The javac compiler would issue a faint sigh, but would still compile everything as before. How did they do it? Type erasure was the magic ingredient. When they compiled the class ArrayList, the generic type parameter was erased and replaced with Object. Even the E[] was erased to Object[]. In Java 6, they changed the element array in ArrayList to the more honest Object[].

泛型虽然被加入到了 Java 体系总但我们完全可以不去使用它,编译器只是会有一个警告标志,但不影响程序的执行。他们怎么做到的?这就是类型擦除(Java 泛型的内部机制,有兴趣的朋友可以百度一下),当我们编译 ArrayList 这个类时,泛型类型是被擦除掉的,被 Object(对象的祖宗)这个类型取代,甚至异常占位符 E[]也被替换成了 Object[] (百度一下泛型占位符的基本概念),在 Java 1.6 版本,他们把 ArrayList 里装载数据的类型都改变成了 Object[]。

1. private transient Object[] elementData;

有兴趣的可以去百度一下这一行代码,深入的理解一下 ArrayList 这个使用非常频繁的集合。
(这部分看不明白不影响后面的阅读)

By not distinguishing at runtime between ArrayList<String> and ArrayList<Integer>, we allowed Java programmers to still shoot themselves in the foot like so:

如果不去关心 ArrayList<String> 和 ArrayList<Integer> 会出现的问题,我们依然允许程序员去拿石头砸自己的脚,如下面的代码:

import java.util.*; public class FootShootJava5{ public static void main(String... args) { List<String> names = new ArrayList<>(); Collections.addAll(names, "John", "Anton", "Heinz"); List huh = names; List<Integer> numbers = huh; numbers.add(42); } }

Sure, javac would emit a warning, but at runtime everything would appear to work. It was only when we retrieved elements from ArrayList that a cast to String was inserted into the client code and then a ClassCastException would jump in our faces. This is an example of an exception that is thrown late. A while after the incorrect object has been inserted into the ArrayList, we discover that it wasn't a String after all, thus if we add the following we see the problem:

这段代码并不会报错,一切运行正常,但是当我们从集合中取出数据并加以操作的时候,异常就会跳到我们脸上,这种异常是一种_后期异常(暂时这么翻译,在本例意思是异常并没有出现在不同类型数据插入时,而是在使用时才出现)_, 下面的例子中解释了这一点:

import java.util.*; import static java.util.stream.Collectors.*; public class FootShootJava8 { public static void main(String... args) { List<String> names = new ArrayList<String>(); Collections.addAll(names, "John", "Anton", "Heinz"); List huh = names; List<Integer> numbers = huh; //应该出现异常的位置,因为插入了非String类型的数据,但这一行并没有抛出异常,而是在下一行抛出了 numbers.add(42); //stream:jdk1.8新特性,可百度一下StreamAPI,下面这行代码意思是将集合中的所有元素连接在一起,以+号分隔开 //这一行抛出了类型转换异常 System.out.println(names.stream().collect(joining("+"))); } }

(StreamAPI 相关博文:http://blog.csdn.net/u010425776/article/details/52346644)

esults in a rather grumpy:

结果让人很暴躁

ClassCastException: Integer cannot be cast to CharSequence at ReduceOps$3ReducingSink.accept() at ArrayList$ArrayListSpliterator.forEachRemaining() at AbstractPipeline.copyInto() at AbstractPipeline.wrapAndCopyInto() at ReduceOps$ReduceOp.evaluateSequential() at AbstractPipeline.evaluate() at ReferencePipeline.collect() at FootShootJava8.main

Since the exception is thrown late, it results in wasted programmer effort searching for where the wrong type could have been inserted into the list.

异常在运行时抛出,而且抛出的位置让程序员很难找到问题所在,浪费了大量的时间。

And yet there has always been a better way, even in Java 5. We can wrap our List object with a checkedList. This way, every time we add an element, it is checked that it is of the correct type. The ClassCastException thus happens during the add(42), rather than much later. For example:

但是总有办法来解决这个问题,甚至在 java1.5 我们也能进行集合的检查,有种方法可以在数据插入集合时就可以去检查数据类型是否正确,在 add(42) 这一行执行时就可以抛出异常不就是我们想要的?看下面的代码:

import java.util.*; import static java.util.stream.Collectors.*; public class FootShootWithSafetyCatch { public static void main(String... args) { List<String> names = Collections.checkedList(new ArrayList<String>(), String.class); Collections.addAll(names, "John","Anton","Heinz"); List huh = names; List<Integer> numbers = huh; numbers.add(42); //异常将会出现在这一行 System.out.println(names.stream().collect(joining("+"))); } }

We would still get a ClassCastException, but at the place where the damage was done:

我们依然会触发一个类型转换异常,但是这次抛出的位置正是错误出现的位置。

ClassCastException: Attempt to insert class Integer element into collection with element type class String at java.util.Collections$CheckedCollection.typeCheck() at java.util.Collections$CheckedCollection.add() at FootShootWithSafetyCatch.main

The checked collection would also discover objects that are added via reflection and throw a ClassCastException. It could not safeguard against "deep reflection", but then not much can.

这个集合检查功能同样可以用于反射检查,抛出类型转换异常,有兴趣的可以去查阅资料,但不能去应付“深度反射”(反射层数较多),但这并不是什么大问题。

You might wonder why I am writing about a method that was added in Java 5? The reason is that hardly anybody I speak to has heard of Collections.checkedCollection() and its derivatives. It is useful to make your collections just a bit more robust against accidental or deliberate tomfoolery.

你肯定问为什么我要拿 java 1.5 来讲这个例子,原因是我想强调一下很少有人知道 Collections.checkedCollection() 和他的衍生物,这是在工作中能让我们的代码更加健壮且避免发生一些愚蠢的问题和浪费不必要的时间。

It can also be a quick and easy way to debug any ClassCastException you might discover in your system. Wrap the collection in a checked exception and the guilty party will quickly come to the fore.

这也是一种快速的方式帮助我们找到类型转换异常的方式,把集合包装起来好让问题尽快的暴露出来。

Oh one last thing, completely unrelated to Java, but definitely related to our profession. Today also marks one year since I started my running streak, running at least one mile a day, in snow, rain, lightning and 48C heat. It's been fun and a great way to think about all sorts of things. I've had far more energy, have slept better and have produced more this year than in many previous years. If you're a couch potato, I can only recommend you try Streak Running and join me in the list of people who've run for at least one year, every day. No excuses.

oh. 还有一件很重要的事,跟 Java 没关系,但是对我们的职业很有好处,今天已经是我连续跑步一年的日子,每天至少跑一公里,不管是刮风下雪,闪电还是 48 度的桑拿天,对我们做事还是工作都非常有好处,我觉得我比之前更有能量了,吃的好睡的好,工作状态比前几年要好太多了,如果你是一个懒癌患者(couch potato?)我非常的建议你跟我一样加入跑步的行列,坚持一年你将看到非常显著的效果。

Kind regards from Crete

Heinz

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3198 引用 • 8215 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • Notion

    Notion - The all-in-one workspace for your notes, tasks, wikis, and databases.

    10 引用 • 77 回帖 • 1 关注
  • 黑曜石

    黑曜石是一款强大的知识库工具,支持本地 Markdown 文件编辑,支持双向链接和关系图。

    A second brain, for you, forever.

    22 引用 • 214 回帖 • 1 关注
  • Google

    Google(Google Inc.,NASDAQ:GOOG)是一家美国上市公司(公有股份公司),于 1998 年 9 月 7 日以私有股份公司的形式创立,设计并管理一个互联网搜索引擎。Google 公司的总部称作“Googleplex”,它位于加利福尼亚山景城。Google 目前被公认为是全球规模最大的搜索引擎,它提供了简单易用的免费服务。不作恶(Don't be evil)是谷歌公司的一项非正式的公司口号。

    49 引用 • 192 回帖
  • 开源

    Open Source, Open Mind, Open Sight, Open Future!

    411 引用 • 3588 回帖
  • OpenCV
    15 引用 • 36 回帖
  • CentOS

    CentOS(Community Enterprise Operating System)是 Linux 发行版之一,它是来自于 Red Hat Enterprise Linux 依照开放源代码规定释出的源代码所编译而成。由于出自同样的源代码,因此有些要求高度稳定的服务器以 CentOS 替代商业版的 Red Hat Enterprise Linux 使用。两者的不同在于 CentOS 并不包含封闭源代码软件。

    239 引用 • 224 回帖 • 1 关注
  • GitBook

    GitBook 使您的团队可以轻松编写和维护高质量的文档。 分享知识,提高团队的工作效率,让用户满意。

    3 引用 • 8 回帖 • 1 关注
  • Angular

    AngularAngularJS 的新版本。

    26 引用 • 66 回帖 • 548 关注
  • 服务

    提供一个服务绝不仅仅是简单的把硬件和软件累加在一起,它包括了服务的可靠性、服务的标准化、以及对服务的监控、维护、技术支持等。

    41 引用 • 24 回帖 • 3 关注
  • InfluxDB

    InfluxDB 是一个开源的没有外部依赖的时间序列数据库。适用于记录度量,事件及实时分析。

    2 引用 • 88 关注
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    948 引用 • 1460 回帖 • 1 关注
  • JetBrains

    JetBrains 是一家捷克的软件开发公司,该公司位于捷克的布拉格,并在俄国的圣彼得堡及美国麻州波士顿都设有办公室,该公司最为人所熟知的产品是 Java 编程语言开发撰写时所用的集成开发环境:IntelliJ IDEA

    18 引用 • 54 回帖 • 5 关注
  • RemNote
    2 引用 • 16 回帖 • 7 关注
  • Dubbo

    Dubbo 是一个分布式服务框架,致力于提供高性能和透明化的 RPC 远程服务调用方案,是 [阿里巴巴] SOA 服务化治理方案的核心框架,每天为 2,000+ 个服务提供 3,000,000,000+ 次访问量支持,并被广泛应用于阿里巴巴集团的各成员站点。

    60 引用 • 82 回帖 • 612 关注
  • 数据库

    据说 99% 的性能瓶颈都在数据库。

    345 引用 • 742 回帖
  • 单点登录

    单点登录(Single Sign On)是目前比较流行的企业业务整合的解决方案之一。SSO 的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。

    9 引用 • 25 回帖 • 3 关注
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖 • 2 关注
  • H2

    H2 是一个开源的嵌入式数据库引擎,采用 Java 语言编写,不受平台的限制,同时 H2 提供了一个十分方便的 web 控制台用于操作和管理数据库内容。H2 还提供兼容模式,可以兼容一些主流的数据库,因此采用 H2 作为开发期的数据库非常方便。

    11 引用 • 54 回帖 • 668 关注
  • SOHO

    为成为自由职业者在家办公而努力吧!

    7 引用 • 55 回帖 • 3 关注
  • V2Ray
    1 引用 • 15 回帖
  • Gzip

    gzip (GNU zip)是 GNU 自由软件的文件压缩程序。我们在 Linux 中经常会用到后缀为 .gz 的文件,它们就是 Gzip 格式的。现今已经成为互联网上使用非常普遍的一种数据压缩格式,或者说一种文件格式。

    9 引用 • 12 回帖 • 164 关注
  • BAE

    百度应用引擎(Baidu App Engine)提供了 PHP、Java、Python 的执行环境,以及云存储、消息服务、云数据库等全面的云服务。它可以让开发者实现自动地部署和管理应用,并且提供动态扩容和负载均衡的运行环境,让开发者不用考虑高成本的运维工作,只需专注于业务逻辑,大大降低了开发者学习和迁移的成本。

    19 引用 • 75 回帖 • 668 关注
  • Hibernate

    Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,使得 Java 程序员可以随心所欲的使用对象编程思维来操纵数据库。

    39 引用 • 103 回帖 • 724 关注
  • Mac

    Mac 是苹果公司自 1984 年起以“Macintosh”开始开发的个人消费型计算机,如:iMac、Mac mini、Macbook Air、Macbook Pro、Macbook、Mac Pro 等计算机。

    168 引用 • 597 回帖
  • 链滴

    链滴是一个记录生活的地方。

    记录生活,连接点滴

    173 引用 • 3849 回帖
  • 996
    13 引用 • 200 回帖 • 3 关注
  • 持续集成

    持续集成(Continuous Integration)是一种软件开发实践,即团队开发成员经常集成他们的工作,通过每个成员每天至少集成一次,也就意味着每天可能会发生多次集成。每次集成都通过自动化的构建(包括编译,发布,自动化测试)来验证,从而尽早地发现集成错误。

    15 引用 • 7 回帖