Generic types advantage

  1. Parameterized type can provide erroneous check in compile time.

    // Parameterized collection type - typesafe

    private final Collection<Stamp>stamps = ... ;

  2. 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>

Item 23

Actual type parameter

String

Item 23

Generic Type List<E>

List<E>

Item 23

Formal type parameter

E

Item 23

Unbounded wildcard type

List<?>

Item 23

Raw type

List

Item 23

Bounded type parameter

<E extends Number>

Item 26

Recursive type bound

<T extends Comparable<T>>

Item 27

Bonded wildcard type

List<? Extends Number>

Item 28

Generic method

Static <E> List<E> asList(E[] a)

Item 27

Type token

String.class

Item 29

Effective Java 23 Don't use raw types in new code的更多相关文章

  1. 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 ...

  2. 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 ...

  3. 《Effective Java》读书笔记 - 5.泛型

    Chapter 5 Generics Item 23: Don't use raw types in new code 虽然你可以把一个List<String>传给一个List类型(raw ...

  4. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  5. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  6. Effective Java 第三版——23. 优先使用类层次而不是标签类

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  7. Effective Java 第三版——26. 不要使用原始类型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  8. Effective Java 第三版——30. 优先使用泛型方法

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  9. Effective Java笔记一 创建和销毁对象

    Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...

随机推荐

  1. Java魔法堂:以Windows服务的形式运行Java程序

    一.前言 由于防止维护人员误操作关闭Java控制台程序,因此决定将其改造为以Windows服务的形式运行.弄了一个上午总算搞定了,下面记录下来,以供日后查阅. 二.Java Service Wrapp ...

  2. ios基础之入门(一)

    最近找到了一个可以接触ios开发的职位,可以系统的学习和练习了.先从最基本的开始: 一.获取控件的两种方式 1)第一种,也是经常使用的一种,通过IBOutlet方式.直接按住control键,将控件和 ...

  3. struts2基础——自定义拦截器

    一.自定义拦截器 默认的拦截器能实现的功能是有限的,Struts2 支持自定义拦截器. 二.拦截器类 1.实现 Interceptor 接口 2.继承 AbstractInterceptor 抽象类, ...

  4. javaScript一些函数包括调试方法(二)

    Number():设法把括号里面的值,转换成一个数,转换不了为数字的话,就返回NaN. 注意:Number()函数,会拒绝任何包含,非数字字符的字符串(阿拉伯数字.一个有效的小数位.+.-符号是允许的 ...

  5. Unity多语言本地化改进版

    简介 之前捣鼓过一个通过csv配置游戏多语言支持的小工具,但是发现使用过程中,通过notepad++去进行转码很不方便,并且直接将配置的csv不加密的放在游戏中心里感觉不是很踏实 于是乎~~ 新的方案 ...

  6. 【JavaScript回顾】继承

    组合继承 组合继承(combination inheritance),有时候也叫做伪经典继承,指的是将原型链和借用构造函数的 技术组合到一块,从而发挥二者之长的一种继承模式.其背后的思路是使用原型链实 ...

  7. 批处理安装Windows服务,提示"InstallUtil.exe"不是内部命令也不是外部命令解决方式

    今天在测试一个C#写的windows服务的时候,在用bat进行调用cmd安装的时候, cd C:\Windows\Microsoft.NET\Framework\v2.0.50727 InstallU ...

  8. 解决android引用library project错误

    在andriod项目中引用另一个library project时,报 The container 'Android Dependencies' references non existing libr ...

  9. div与>div区别小结

    两者之间的区别:例如div span得到的是div下所有的span元素,而div>span则是取得的div下第一级的span元素. 示例代码如下: <!DOCTYPE html> & ...

  10. 重新想象 Windows 8.1 Store Apps (78) - 控件增强: ScrollViewer, FlipView, Popup

    [源码下载] 重新想象 Windows 8.1 Store Apps (78) - 控件增强: ScrollViewer, FlipView, Popup 作者:webabcd 介绍重新想象 Wind ...