Effective Java 23 Don't use raw types in new code
Generic types advantage
- Parameterized type can provide erroneous check in compile time.
// Parameterized collection type - typesafe
private final Collection<Stamp>stamps = ... ;
- You no longer have to cast manually when removing elements from collections.
// for-each loop over a parameterized collection - typesafe
for (Stamp s : stamps) { // No cast
... // Do something with the stamp
}
or a traditional forloop:
// for loop with parameterized iterator declaration - typesafe
for (Iterator<Stamp> i = stamps.iterator(); i.hasNext(); ) {
Stamp s = i.next(); // No cast necessary
... // Do something with the stamp
}
Note
If you use raw types, you lose all the safety and expressiveness benefits of generics.
You lose type safety if you use a raw type like List, but not if you use a parameterized type like List<Object>.
// Uses raw type (List) - fails at runtime!
public static void main(String[] args) {
List<String> strings = new ArrayList<String>();
unsafeAdd(strings, new Integer(42));
String s = strings.get(0); // Compiler-generated cast
}
private static void unsafeAdd(List list, Object o) {
list.add(o);
}
This program compiles, but because it uses the raw type List, you get a warning:
Test.java:10: warning: unchecked call to add(E) in raw type List
list.add(o);
^
if you run the program, you get a ClassCastException when the program tries to cast the result of the invocation strings.get(0) to a String . This is a compiler-generated cast, so it's normally guaranteed to succeed, but in this case we ignored a compiler warning and paid the price.
unbounded wildcard types - Set<?>
If you want to use a generic type but you don't know or care what the actual type parameter is, you can use a question mark instead.
// Unbounded wildcard type - typesafe and flexible
static int numElementsInCommon(Set<?> s1, Set <?> s2) {
int result = 0;
for (Object o1 : s1)
if (s2.contains(o1))
result++;
return result;
}
|
Name |
Example |
Feature |
Disadvantage |
|
Raw type |
List |
Can add anything |
No type security check. |
|
Generic type |
List<Object> |
Provide type check. |
Generic type information is erased at runtime (Item 25) which means that List<String>.class and List<?> are illegal. |
|
Unbounded wildcard type |
List<?> |
You can't put any element (other than null) into a Collection<?> but null. |
This is the preferred way to use the instanceof operator with generic types
// Legitimate use of raw type - instanceof operator
if (o instanceof Set ) { // Raw type
Set<?> m = (Set<?>) o; // Wildcard type
...
}
Summary
Raw types can lead to exceptions at runtime, so don't use them in new code;
Set<Object> is a parameterized type representing a set that can contain objects of any type;
Set<?> is a wildcard type representing a set that can contain only objects of some unknown type, and Set is a raw type, which opts out of the generic type system. The first two are safe and the last is not.
|
Term |
Example |
Item |
|
Parameterized type |
List<String> |
|
|
Actual type parameter |
String |
|
|
Generic Type List<E> |
List<E> |
|
|
Formal type parameter |
E |
|
|
Unbounded wildcard type |
List<?> |
|
|
Raw type |
List |
|
|
Bounded type parameter |
<E extends Number> |
|
|
Recursive type bound |
<T extends Comparable<T>> |
|
|
Bonded wildcard type |
List<? Extends Number> |
|
|
Generic method |
Static <E> List<E> asList(E[] a) |
|
|
Type token |
String.class |
Effective Java 23 Don't use raw types in new code的更多相关文章
- Effective Java 50 Avoid strings where other types are more appropriate
Principle Strings are poor substitutes for other value types. Such as int, float or BigInteger. Stri ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- 《Effective Java》读书笔记 - 5.泛型
Chapter 5 Generics Item 23: Don't use raw types in new code 虽然你可以把一个List<String>传给一个List类型(raw ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java 第三版——23. 优先使用类层次而不是标签类
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版——26. 不要使用原始类型
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java 第三版——30. 优先使用泛型方法
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java笔记一 创建和销毁对象
Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...
随机推荐
- Java异步回调
作者:禅楼望月(http://www.cnblogs.com/yaoyinglong) 1.开始讲故事: 午饭的时候到了,可是天气太冷,根本不想出办公室的门,于是你拨通了某饭店的订餐电话“喂!你好 ...
- 哀悼我的第一次"创业"经历
下周考完最后一科,大学四年时光基本上算是落下帷幕,剩下的就只是整整毕业设计了.如果按照正常的节奏,这个学期应该能够搞完毕业设计的2/3,但无奈还在广州的一家公司里面实习,没有多少时间弄,得拖到3月了. ...
- python编码声明的位置很重要
python在3.x版本之前,编码一直是一个很头痛的问题.在代码中如果要使用中文,通常都要在文件的头部注明# -*- coding:utf-8 -*- 这样IDE或者解释器才会智能的转换编码. 这其中 ...
- Sql [hierarchyid]类型如何动态插入层级数据
[hierarchyid] 是个不错的数据类型,能够方便的操作树型结构,网上找了很多资料没找到如何做到动态插入节点的例子,只好从MSDN认真看了下资料写出了一个DEMO CREATE TABLE Em ...
- 2013/11/22工作随笔-缓存是放在Model层还是放在Controller层
web网站的典型代码框架就是MVC架构,Model层负责数据获取,Controller层负责逻辑控制,View层则负责展示. 一般数据获取是去mysql中获取数据 但是这里有个问题,我们不会每次请求都 ...
- .Net魔法堂:史上最全的ActiveX开发教程——自动更新、卸载篇
一.前言 B/S模式的特点之一,客户端版本升级相对简单.快捷,适合产品的快速迭代.而ActiveX组件的自动更新同样也继承了这一优点.下面我们一起来了解吧! 二.二话不说更新ActiveX 1. 设置 ...
- Android的init过程(二):初始化语言(init.rc)解析
Android的init过程(一) 本文使用的软件版本 Android:4.2.2 Linux内核:3.1.10 在上一篇文章中介绍了init的初始化第一阶段,也就是处理各种属性.在本文将会详细分析i ...
- 【第〇课】用更好的IDE开发
推荐的IDE IntelliJ IDEA JetBrains是一家捷克的软件开发公司,这家公司做出了很多的优秀的IDE,有写python的.php的.web前端的……IDEA就是其中一款非常优秀的ja ...
- [Tool] PowerDesigner
一般项目的生命周期: 1.需求分析 2.需求规格说明书 3.总体设计 4.详细设计 5.编码实现 6.测试,试运行. 7.验收 8.后期维护 PowerDesigner 可以把软件生命周期的每一个阶段 ...
- 用UltraISO制作支持windows 7的U盘启动盘
用UltraISO制作U盘启动盘,有人写过,我也看过,不过依照网上的那些文章,成功的并不多,经过几次试验,在不同的主板环境下成功概率高的方法应该如下: 1. UltraISO建议9.3以上 2. ...