Effective Java - item 26 & item 27

本文讨论了在编程中使用泛型的重要性,特别是关于类型安全和表达力。强调了不应该使用原始类型(raw types),因为它们会丧失泛型提供的安全性。示例中展示了使用未检查警告的情况,如不安全的转换和方法调用,并指出应在可能的情况下消除这些警告。如果无法消除,应该提供注解以证明代码是类型安全的。同时,提倡缩小@SuppressWarnings注解的使用范围,并在使用时添加注释说明原因。
摘要由CSDN通过智能技术生成

Item 26: Don’t use raw types

If you use raw types, you lose all the safety and expressiveness benefits of generics

the raw type List and the parameterized type List<Object>

Set<E> is Set<?> (read “set of some type”)

List<String> (read “list of string”)

String is the actual type parameter corresponding to the formal type parameter E.

the raw type corresponding to List<E> is List

it pays to discover errors as soon as possible after they are made, ideally at compile time. In this case, you don’t discover the error until runtime, long after it has happened, and in code that may be distant from the code containing the error. Once you see the ClassCastException, you have to search through the codebase looking for the method invocation that put the coin into the stamp collection

you lose type safety if you use a raw type such as List, but not if you use a parameterized type such as List<Object>.

a few minor exceptions to the rule that you should not use raw types:

You must use raw types in class literals.

List.class, String[].class, and int.class

wildcard type Set<?>

using raw types can lead to exceptions at runtime, so don’t use them

TermExampleItem
Parameterized typeList<String>Item-26
Actual type parameterStringItem-26
Generic typeList<E>Item-26, Item-29
Formal type parameterEItem-26
Unbounded wildcard typeList<?>Item-26
Raw typeListItem-26
Bounded type parameter<E extends Number>Item-29
Recursive type bound<T extends Comparable<T>>Item-30
Bounded wildcard typeList<? extends Number>Item-31
Generic methodstatic <E> List<E> asList(E[] a)Item-30
Type tokenString.classItem-33

Item 27: Eliminate unchecked warnings

unchecked cast warnings,

unchecked method invocation warnings,

unchecked parameterized vararg type warnings,

and unchecked conversion warnings

Set<Lark> exaltation = new HashSet();
​
Venery.java:4: warning: [unchecked] unchecked conversion
Set<Lark> exaltation = new HashSet();
^ required: Set<Lark>
found: HashSet
​
​
diamond operator  (<>)
Set<Lark> exaltation = new HashSet<>();
​

Eliminate every unchecked warning that you can

If you can’t eliminate a warning, but you can prove that the code that provoked the warning is typesafe, then (and only then) suppress the warning with an @SuppressWarnings("unchecked") annotation.

Always use the SuppressWarnings annotation on the smallest scope possible.

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        return (T[]) Arrays.copyOf(elements, size, a.getClass());
    System.arraycopy(elements, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}
​
ArrayList.java:305: warning: [unchecked] unchecked cast
return (T[]) Arrays.copyOf(elements, size, a.getClass());
^ required: T[]
found: Object[]
​
​
// Adding local variable to reduce scope of @SuppressWarnings
public <T> T[] toArray(T[] a) {
    if (a.length < size) {
        // This cast is correct because the array we're creating
        // is of the same type as the one passed in, which is T[].
        @SuppressWarnings("unchecked") T[] result = (T[]) Arrays.copyOf(elements, size, a.getClass());
        return result;
    }
    System.arraycopy(elements, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}
​

Every time you use a @SuppressWarnings("unchecked") annotation, add a comment saying why it is safe to do so.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值