消除未检查警告

在编译过程中出现warning的时候,我们应该根据编译器的指示来进行修正,让警告消失。

对于不能消除的警告,如果能够引起这个警告的代码是类型安全的话,那么就可以使用注解@SuppressWarnings("unchecked")来禁止这个警告。该注解可以在任意声明上使用,从单独的局部变量到整个类都可以,但我们应该在尽可能小的作用域上使用该注解。永远不要在整个类上使用SuppressWarnings注解。

对于以下的方法,编译的时候会生成warning:

1
2
3
4
5
6
7
8
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;
}
1
2
3
4
ArrayList.java:305: warning: [unchecked] unchecked cast return (T[]) Arrays.copyOf(elements, size, a.getClass());
^
required: T[]
found: Object[]

对于这种情况,我们不能将注解放在返回语句上,因为其不是一个声明。因此我们可以声明一个局部变量来保存返回值,并注解这个局部变量的声明,并且需要在注释里记录禁止warning的原因:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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;
}