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条 ...
随机推荐
- ASP.NET MVC分页实现之改进版-增加同一个视图可设置多个分页
我之前就已经实现了ASP.NET MVC分页(查看该博文),但它有局限性,必须确保在同一个视图中只能有一处分页,若需要在同一个视图中设置多个分页,却无能为力,为此,我重新对原先的代码进行了优化,增加了 ...
- Angular系列----AngularJS入门教程04:迭代器过滤(转载)
我们在上一步做了很多基础性的训练,所以现在我们可以来做一些简单的事情喽.我们要加入全文检索功能(没错,这个真的非常简单!).同时,我们也会写一个端到端测试,因为一个好的端到端测试可以帮上很大忙.它监视 ...
- BLOCK的应用
相比看一下枯燥乏味的对于block的讲解,为什么不从大神的代码中领路它的使用方法呢,了解一下大神是如何使用block的呢,见识它的强大.https://github.com/zwaldowski/Bl ...
- LVS使用整理(1)
开始安装LVS 1)下载相关软件包 mkdir -p /home/tools/cd /home/tools/wget http://www.linuxvirtualserver.org/softwar ...
- Gradle学习系列之一——Gradle快速入门
这是一个关于Gradle的学习系列,其中包含以下文章: Gradle快速入门 创建Task的多种方法 读懂Gradle语法 增量式构建 自定义Property 使用java Plugin 依赖管理 构 ...
- c3p0配置
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN&q ...
- svn状态图标大全
黄色感叹号(有冲突):--这是有冲突了,冲突就是说你对某个文件进行了修改,别人也对这个文件进行了修改,别人抢在你提交之前先提交了,这时你再提交就会被提示发生冲突,而不允许你提交,防止你的提交覆盖了别 ...
- 重构第11天 使用策略代替Switch(Switch to Strategy)
理解:策略就是平常设计模式中所说的策略模式.因为当你有一个庞大的switch方法的时候,每一次新加一个条件,都要去修改这个方法,这样耦合性太高,不易维护也不易扩展.这样我们就可以使用策略的设计模式,使 ...
- Unity实现滑页效果(UGUI)
简介 项目需要...直接展示效果吧: 原理 使用UGUI提供的ScrollRect和ScrollBar组件实现基本滑动以及自己控制每次移动一页来达到滑页的效果. 实现过程 1.创建两个panel,上面 ...
- 《Node.js+MongoDB+AngularJS Web开发》读书笔记及联想
总体介绍 <Node.js+MongoDB+AngularJS Web开发>,于2015年6月出版,是一本翻译过来的书,原书名为<Node.js,MongoDB and Angula ...