Effective Java 学习笔记(23)

来源:互联网 发布:留学生自卑知乎 编辑:程序博客网 时间:2024/05/06 14:55

不要在新代码中使用原生态类型,而应该使用泛型。

泛型的优点:

1. 编译时就会进行类型检查。 当向一个容器中装入对象时,编译器会检查,插入的实例是不是前面声明的类型。而不用等到运行时才会发现,而抛出ClassCastException.

 

2.从集合中取元素不用再进行手工转换,编译器会替你进行隐式的转换。

尽量使用Set<Object>代替Set,  因为原生态不是类型安全的。

在必要时可以使用Set<?>

// 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;
}

例外情况:

1.类文字中必须使用原生态类型:List.class, String[].class, int.class,但List<String>.class不合法。

2.使用instanceof时,只能用原生态。

// Legitimate use of raw type - instanceof operator
if (o instanceof Set) { // Raw type
Set<?> m = (Set<?>) o; // Wildcard type
...
}

原创粉丝点击