Qiita Conference 2025

Qiita史上最多!豪華12名のゲストが登壇

特別講演ゲスト(敬称略)

ymrl、成瀬允宣、鹿野壮、伊藤淳一、uhyo、徳丸浩、ミノ駆動、みのるん、桜庭洋之、tenntenn、けんちょん、こにふぁー

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?