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. Parameter Config

    public class ConfigInfo { public static ScriptsHelper Scripts { get { return new ScriptsHelper(); } ...

  2. 《构建之法》第8、9、10章读书笔记、读后感以及Sprint1总结

    第八章:需求分析 软件需求 人们(用户)的需求五花八门,作为一个软件团队要准确而全面地获取这些需求主要有以下四个步骤: 获取和引导需求.这一步骤也被叫做“需求捕捉”.软件团队需要为用户着想,设身处地, ...

  3. 当我们安装使用时,会出现eclipse启动不了,出现“Java was started but returned exit code=13......”的问题

    安装win8.1后,启动eclipse,也会提示 "java was started but returned exit code=13" 可能是eclipse.ini配置文件错误 ...

  4. 数论 - 高精度Fibonacci数 --- UVa 10183 : How Many Fibs ?

    How many Fibs? Description Recall the definition of the Fibonacci numbers: f1 := 1 f2 := 2 fn := f n ...

  5. Mysql有没有语法可以在增加列前进行判断该列是否存在

    Mysql没有直接的语法可以在增加列前进行判断该列是否存在,需要写一个存储过程完成同样任务,下面例子是:在sales_order表中增加一列has_sent列 drop procedure if ex ...

  6. JdbcTemplate使用总结

    Spring JdbcTemplate 在数据库的操作中,每个业务方法都要得到连接,开启事务,提交事务,回滚,关闭连接等,我们可以把这些做成一个模版,这样,在业务代码中只需要关注业务逻辑即可. MyJ ...

  7. sql语句创建新登录名和设置权限

    use DBName go --新增用户 exec sp_addlogin '用户名','密码','默认数据库名' --添加登录 exec sp_grantdbaccess N'test' --使其成 ...

  8. ahjesus C# Flags 位域略说

    class Program { [Flags] public enum Week { [Description("星期一")] Monday = << , [Descr ...

  9. Visual Studio图片注释image-comments扩展

            有一个开源的Visual Studio小工具image-comments,它用于在源代码注释中插入图片,您可以到这儿下载.目前支持Visual Studio 2010/2012 Sta ...

  10. 研究jdk关于TreeMap 红黑树算法实现

    因为TreeMap的实现方式是用红黑树这种数据结构进行存储的,所以呢我主要通过分析红黑树的实现在看待TreeMap,侧重点也在于如何实现红黑树,因为网上已经有非常都的关于红黑树的实现.我也看了些,但是 ...