LoginSignup
0
0

More than 5 years have passed since last update.

Item 27: Eliminate unchecked warnings

Posted at

27.unchecked warnings は削除せよ

  • コンパイラが出すunchecked warningsを全部消すことができれば、そのコードはタイプセーフ、つまり、実行時にClassCastExceptionを発生させることがなくなる。よって、unchecked warningsは全て消すようにするべきである。
  • すべてのwarningは消すことができないが、タイプセーフであることを証明できた場合は@SuppressWarnings("unchecked")アノテーションを付与する。 タイプセーフであることを証明する前にこのアノテーションを付与してしまうと、コンパイル時にunchecked warnings はでないのに、ClassCastExceptionは出ることとなり、エラー解消を困難にしてしまう。
  • @SuppressWarnings("unchecked")の付与はできるだけ小さいスコープにするべきである。
package tryAny.effectiveJava;

import java.util.Arrays;

public class GenericsTest4 {

    private int size;
    transient Object[] elementData; // non-private to simplify nested class access

    public <T> T[] toArray(T[] a) {
        if (a.length < size) {
            @SuppressWarnings("unchecked")
            T[] result = (T[]) Arrays.copyOf(elementData, size, a.getClass());
            return result;
        }
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
}
  • @SuppressWarnings("unchecked")を使用するときは、なぜそれが安全なのか理由を記載すべき。 記載することによって、コードの理解の助けになるし、誰かが安全でない演算となるような変更を加える機会は減る。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0