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 JS验证和服务端的 双验证 更简单
只用JavaScript验证安全不安全谁都知道,答案是不安全,非常的不安全.因为在客户端进行的验证相当于“让用户自己验证自己”,很明显是不靠谱的.你不能避免一些恶意用户人为的修改自己的表单进行欺骗,也 ...
- CentOS6.5菜鸟之旅:纯转载Linux目录结构
来自:http://www.iteye.com/topic/1125162 使用linux也有一年多时间了 最近也是一直在维护网站系统主机 下面是linux目录结构说明 本人使用的是centos系 ...
- IOS开发UI基础之UIButton
什么是按钮?
- Qt之QAbstractItemView视图项拖拽(二)
一.需求说明 上一篇文章Qt之QAbstractItemView视图项拖拽(一)讲述了实现QAbstractItemView视图项拖拽的一种方式,是基于QDrag实现的,这个类是qt自己封装好了的,所 ...
- IntelliTrace简介
解决无法复现bug所使用的策略是在遇到bug时捕获尽可能多的信息,在使用IntelliTrace进行调试时可以充分利用这些信息.最令人称道的一个功能在于bug本身可以自动修复. 打开IntelliTr ...
- C#反射的应用
项目框架中有一个很实用的方法,它用来获取客户端post的数据,并自动赋值到对象各属性,这样后台少写了很多代码.但是对于有主表.子表的表单,框架中没有提供自动给子表对象各属性赋值的方法,每次都要写很多代 ...
- 设计模式--原型(Prototype)模式
写这些也许有人认为“为了模式而模式”.Insus.NET所想到的,每个大师成为大师之前,也许都得这样做. 走路,从小就开始学,直至现在,谁还不是为了走路而走路?一直重复着...... 很多人没有分享自 ...
- out 和 ref 参数修饰符
整理自MSDN out: out 关键字通过引用传递参数.这与 ref 关键字相似,只不过 ref 要求在传递之前初始化变量.若要使用 out 参数,方法定义和调用方法均必须显式使用 out 关键字. ...
- Visual Studio中附加调试器的方法
添加一个空的C++项目,项目属性配置如图. 命令里写要调试的程序的完整路径. 工作目录写所在目录的路径.
- ASP.NET WebAPI 12 Action的执行
Action的激活大概可以分为如下两个步骤:Action对应方法的调用,执行结果的协商.在WebAPI中由HttpActionInvoker(System.Web.Http.Controllers)进 ...