Effective Java 4

Item 27 不要使用原始类型

1 // Raw collection type - don't do this!
2 // My stamp collection. Contains only Stamp instances.
3 private final Collection stamps = ... ;
1 // Erroneous insertion of coin into stamp collection
2 stamps.add(new Coin( ... )); // Emits "unchecked call" warning
// Raw iterator type - don't do this!
for (Iterator i = stamps.iterator(); i.hasNext(); )
    Stamp stamp = (Stamp) i.next(); // Throws ClassCastException
stamp.cancel();

1、使用原始类型不会产生编译期错误,但会产生运行期错误,增加debug难度。

1 // Parameterized collection type - typesafe
2 private final Collection<Stamp> stamps = ... ;

2、虽然使用原始类型是合法的,但是不应该这样做,这会丧失类型安全以及泛型在表达方面的优势。

3、必须使传递含有参数类型的实例 给 被设计为原始类型的方法 合法,反之亦然。这就是所谓的移植性,为了兼容之前版本。

4、List<String> 是原始类型List 的子类 但不是 List<Object>的子类。

5、使用原始类型会失去类型安全但是 List<Object>不会。

6、当不确定方法的具体参数类型时,也不要使用原始类型。

1 // Use of raw type for unknown element type - don't do this!
2 static int numElementsInCommon(Set s1, Set s2) {
3     int result = 0;
4     for (Object o1 : s1)
5         if (s2.contains(o1))
6             result++;
7     return result;
8 }

而应该使用<?>:

1 // Uses unbounded wildcard type - typesafe and flexible
2 static int numElementsInCommon(Set<?> s1, Set<?> s2) { ... }

7、在 class literals 中必须使用原始类型,例如List,class,String[].class。

8、在 instanceof 操作符中必须使用原始类型:

1 // Legitimate use of raw type - instanceof operator
2 if (o instanceof Set) { // Raw type
3 Set<?> s = (Set<?>) o; // Wildcard type
4 ...
5 }

注意第三行的类型转换是必须的。

扫描二维码关注公众号,回复: 1753825 查看本文章

9、<Object>是指能放入任何对象,<?>是指能放入 任何一种 目前未知的对象

猜你喜欢

转载自www.cnblogs.com/WutingjiaWill/p/9224071.html