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. [linux]删除目录下的一类文件

    find 目录 -name "*.类型" | xargs rm -f 通过find命令,查找指定目录下的某一类型的文件.并通过管道传递给xargs,执行后面的rm -f命令. 最终 ...

  2. 高效查看MySQL帮助文档的方法

    在mysql的使用过程中, 可能经常会遇到以下问题: 某个操作语法忘记了, 如何快速查找? 如何快速知道当前版本上某个字段类型的取值范围? 当前版本都支持哪些函数?希望有例子说明.. 当前版本是否支持 ...

  3. python之IO多路复用

    在python的网络编程里,socetserver是个重要的内置模块,其在内部其实就是利用了I/O多路复用.多线程和多进程技术,实现了并发通信.与多进程和多线程相比,I/O多路复用的系统开销小,系统不 ...

  4. 如何根据iframe内嵌页面调整iframe高宽续篇

    接着昨天的工作 如何根据iframe内嵌页面调整iframe高宽 来说,按照文章中说的第二种方法实现代码如下: 实现 A.com/detail/view 页面的iframe代码如下: <ifra ...

  5. 浅谈mysql的两阶段提交协议

    前两天和百度的一个同学聊MySQL两阶段提交,当时自信满满的说了一堆,后来发现还是有些问题的理解还是比较模糊,可能是因为时间太久了,忘记了吧.这里再补一下:) 5.3.1事务提交流程 MySQL的事务 ...

  6. UICollectionView使用以及与UITableView的区别

    在开始前我们在这先附一段最简单的代码 - (void)viewDidLoad { [super viewDidLoad]; UICollectionViewFlowLayout *layout = [ ...

  7. nodejs+express+jade给我baby做个小相册

    去年年底迎来了my little star.从此人生多了一个最重要的牵挂.生了宝宝全家人都太忙了.最近宝宝稍微大点了,终于有空可以研究下技术了.这是14年第一帖.废话不多了.开始吧 1.安装NTVS ...

  8. 暴力 + 贪心 --- Codeforces 558C : Amr and Chemistry

    C. Amr and Chemistry Problem's Link: http://codeforces.com/problemset/problem/558/C Mean: 给出n个数,让你通过 ...

  9. Python入门笔记(14):Python的字符编码

    一.字符编码中ASCII.Unicode和UTF-8的区别 点击阅读:http://www.cnblogs.com/kingstarspe/p/ASCII.html 再推荐一篇相关博文:http:// ...

  10. cmd命令行编译和运行java程序报错 NoClassDefFoundError

    首先,当在运行java程序出现这个错误时,首先考虑是不是路径或者未指定正确的包名,例如当运行下面这个文件时: package cn.wgh.socket; public class HelloWorl ...