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条 ...
随机推荐
- 第十二篇 SQL Server代理多服务器管理
本篇文章是SQL Server代理系列的第十二篇,详细内容请参考原文 在这一系列的上一篇,我们查看了维护计划,一个维护计划可能会创建多个作业,多个计划.你还简单地看了SSIS子系统,并查看了维护计划作 ...
- python编码问题的最终分析
python初学者,往往因为字符编码的问题而苦恼不已,本人也是阅读了大量的博客,再进行了一定的测试,基本搞清楚了编码问题的前因后果.下面一段代码是在python3.5上的,以它为例进行讲解(请忽略糟糕 ...
- ASP.NET 文件上传类 简单好用
调用: UploadFile uf = new UploadFile(); /*可选参数*/ uf.SetIsUseOldFileName(true);//是否使用原始文件名作为新文件的文件名(默认: ...
- 从IE6到IE11上运行WebGL 3D遇到的各种坑
这篇<基于HTML5的电信网管3D机房监控应用>基于WebGL技术的应用让少同学对HTML5 3D的应用产生了兴趣和信心,但有不少网友私信询问WebGL如何运行在老的IE678910浏览器 ...
- hibernate用注解(annotation)配置sequence
@Id@SequenceGenerator(name="sequenceGenerator",sequenceName="ACTIVITIESSCOPE_SEQ" ...
- 【JS复习笔记】00 序
作为一个前端苦手,说是复习,你就当我是重学好了. 好吧,我当然不可能抱着一个砖头去复习,所以捡了本薄的来读——<JavaScript语言精粹>. 当初带我的人说这本书挺好,就看这本书好了. ...
- 在phpwind内容页使用百度分享进行图片分享
在phpwind内容页使用百度分享进行图片分享时,百度分享默认提取到的图片不一定是主题正文内容中的图片,需要使用百度提供的配置机制自行调整. 整个代码添加的位置在此不论,主要原理是在主题正文区域提取图 ...
- vim编辑器,管道,输入输出重定向
1.vim的认识及其一些常用指令 a, 认识vim的命令行模式和插入模式: 当vim运行后默认进入该模式,他可以控制屏幕光标的移动,字符.字或行的删除,移动复制某区段及进入Insert mode下,或 ...
- php中的常用数组函数(二)(数组元素过滤 array_filter())
array_filter($arr, 'filter_func'); //参数1,要过滤的数组 //参数2,过滤的函数,返回false时,不添加这个元素,返回true添加这个元素. 示例代码: /** ...
- php中设定一个全局异常处理。全局catch。默认catch。默认异常处理
<?php function handleMissedException($e) { echo "Sorry, something is wrong. Please try again ...