在使用泛型的时候会面临着很多出现警告的情况,我们要尽可能解决这些警告,有些警告无法消除,但是我们可以证明引起警告的代码是类型安全的,则可以使用@SuppressWarnings(“unchecked”)来禁止这条警告。如果不解决这些没啥问题的警告,当真正的错误和警告出现时会被淹没,不好调试。
    例子:

    1. public <T> T[] toArray(T[] a) {
    2. if (a.length < size)
    3. return (T[]) Arrays.copyOf(elements, size, a.getClass());
    4. System.arraycopy(elements, 0, a, 0, size);
    5. if (a.length > size)
    6. a[size] = null;
    7. return a;
    8. }
    9. 如果编译ArrayList类,则该方法会生成此警告:
    10. ArrayList.java:305: warning: [unchecked] unchecked cast
    11. return (T[]) Arrays.copyOf(elements, size, a.getClass());
    12. ^
    13. required: T[]
    14. found: Object[]

    返回语句中设置SuppressWarnings注解是非法的,因为它不是一个声明。 你可能会试图把注释放在整个方法上,但是不要这要做。 相反,声明一个局部变量来保存返回值并标注它的声明,如下所示:

    1. // Adding local variable to reduce scope of @SuppressWarnings
    2. public <T> T[] toArray(T[] a) {
    3. if (a.length < size) {
    4. // This cast is correct because the array we're creating
    5. // is of the same type as the one passed in, which is T[].
    6. @SuppressWarnings("unchecked") T[] result =
    7. (T[]) Arrays.copyOf(elements, size, a.getClass());
    8. return result;
    9. }
    10. System.arraycopy(elements, 0, a, 0, size);
    11. if (a.length > size)
    12. a[size] = null;
    13. return a;
    14. }

    每当使用@SuppressWarnings(“unchecked”)注解时,请添加注释,说明为什么是安全的。 这将有助于他人理解代码,更重要的是,这将减少有人修改代码的可能性,从而使计算不安全。 如果你觉得很难写这样的注释,请继续思考。 毕竟,你最终可能会发现未经检查的操作是不安全的。
    总结:未经检查的警告是重要的。 不要忽视他们。 每个未经检查的警告代表在运行时出现ClassCastException异常的可能性。 尽你所能消除这些警告。 如果无法消除未经检查的警告,并且可以证明引发该警告的代码是安全类型的,则可以在尽可能小的范围内使用 @SuppressWarnings(“unchecked”)注解来禁止警告。 记录你决定在注释中抑制此警告的理由。