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条 ...
随机推荐
- es6新特性学习
本文用来记录一下es6的新特性,持续更新.... es6在前端目前还不能大面试使用,包括移动端兼容也不好.不过在node中已可以使用其中96%的特性.也可使用一些插件将es6转化为es5,比如babl ...
- Android 学习笔记之AndBase框架学习(七) SlidingMenu滑动菜单的实现
PS:努力的往前飞..再累也无所谓.. 学习内容: 1.使用SlidingMenu实现滑动菜单.. SlidingMenu滑动菜单..滑动菜单在绝大多数app中也是存在的..非常的实用..Gith ...
- Html5+css3+angularjs+jquery+webAPi 开发手机web(一)
前言 随着浏览器的发展 HTML5+CSS3 的使用也越来越广泛,一直想学这个,想学那个折腾下来几乎没学到什么东西.工作经验告诉我,要掌握一门技术,就需要在项目中去磨练, 所以我就准备开发一个手机端的 ...
- C#中国象棋+游戏大厅 服务器 + 客户端源码
来源:www.ajerp.com/bbs C#中国象棋+游戏大厅 服务器 + 客户端源码 源码开源 C#版中国象棋(附游戏大厅) 基于前人大虾的修改版 主要用委托实现 服务器支持在线人数,大厅桌数的设 ...
- 译 PrestaShop开发者指南 第四篇 深入PrestaShop核心开发
## 访问数据库 ### 数据库结构 PrestaShop的数据库表默认带有ps_的前缀,前缀在安装时可以自定义. 所有表名都是小写,以下划线分割.当一个表表示要在两个实体间建立连接时,表名中两个实体 ...
- 使用SignalR+Asp.net创建实时聊天应用程序
一.概述: 使用 ASP.NET 那么 SignalR 2 创建一个实时聊天应用程序.将 SignalR 添加 MVC 5 应用程序中,并创建聊天视图发送并显示消息. 在Demo中,将学习Signal ...
- 小白学Linux(五)--VI/VIM编辑器
我们操作文件,终究离不开编辑文件,对文件内容的编辑,Linux系统下,我们通常使用VI/VIM来编辑文件.VI是每个Linux都会自带的文本编辑器,VIM是VI的增强版,可能有些发行版本没有自带,可以 ...
- C#6.0语法糖剖析(二)
1.索引初始化 使用代码 ] = ] = ] = "thirteen"}; 编译器生成的代码 Dictionary<int, string> dictionary2 = ...
- HTML · 图片热点,网页划区,拼接,表单
图片热点: 规划出图片上的一个区域,可以做出超链接,直接点击图片区域就可以完成跳转的效果. 网页划区: 在一个网页里,规划出一个区域用来展示另一个网页的内容. 网页的拼接: 在一个网络页面内,规划出多 ...
- 浅谈ES6中的Proxy
Proxy是一个很有趣的对象,它能够修改某些操作的默认行为,等同于在语言层面做出修改,属于一种‘元编程’,即对编程语言进行编程. Proxy其实很好理解,就是在目标对象之前架设一层拦截,外界的访问都得 ...