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. Python+Selenium进行UI自动化测试项目中,常用的小技巧3:写入excel表(python,xlsxwriter)

    我们在项目中可能用到excel表生成,下面的代码就是对excel表的操作: import xlsxwriter import datetime class write_excel(): def __i ...

  2. [Tool] 常用开发工具注册码(持续更新)

    OS win10 激活 命令行 打开命令提示符( 管理员 ) 输入 slmgr /ipk W269N-WFGWX-YVC9B-4J6C9-T83GX 回车 再输入 slmgr /skms kms.xs ...

  3. 团队项目SCRUM项目6.0 7.0

    6.0----------------------------------------------------- sprint演示 1.坚持所有的sprint都结束于演示. 团队的成果得到认可,会感觉 ...

  4. javaScript一些函数--Math()

    1.不能显式地创建一个Math对象,直接使用它就可以了: 2.Math对象不能存储数据,和String,Date对象不同: 3.前面知道了parseInt()函数会通过消去小数点后面的一切,来使一个小 ...

  5. 译:重置/还原Windows IIs设置为默认设置

    译文出处:http://www.codeproject.com/Tips/870858/Reset-Restore-IIS-Settings-to-its-Default-in-Windo 简介: I ...

  6. 【iOS】线程安全的文件读写

    前段时间看了一遍GCD(Grand Central Dispatch)多线程,GCD是苹果为多核开发提供的解决方案 多线程最常见的问题就是读写,比如数据库读写,文件读写,读取是共享的,写是互斥,允许多 ...

  7. 快捷获取浏览器(navigator对象)的全部属性

    理论:     navigator对象包含关于web浏览器的信息,浏览器的类型,版本信息都可以从该对象获取. 属性 说明 appCodeName 浏览器代码说明 appName 浏览器名称 appVe ...

  8. MySQL SQL模式匹配

    MySQL提供标准的SQL模式匹配,SQL模式匹配允许你使用“_”匹配任何单个字符,而“%”匹配任意数目字符(包括零字符).. 关于SQL模式匹配:http://dev.mysql.com/doc/r ...

  9. 程序设计模式 —— State 状态模式

    我应该如何阅读? 本文将使用优雅的文字风格来告诉你什么是状态模式. 注意: 1.在阅读本文之前请保证你已经掌控了 面对对象的思想与 多态的基本概念,否则将难以理解. 2.本文实现将用C++实现,你不一 ...

  10. pbfunc外部函数扩展应用-在Powerbuilder中进行Http的GET、POST操作

    利用PBFunc扩展函数进行Http的操作时,需要对n_pbfunc_http的以下几个函数进行参数设置: of_set_URL(...)//要进行GET或POST的url,必须 of_set_Con ...