3

jdkソースコードを読むと、注釈が見つかりますが、なぜここで使用されたのかわかりませんか?
Javaで「@SuppressWarnings( "unchecked")」を使用すると何が得られますか?
いつ使用する必要がありますか、またその理由は何ですか?
jdkソースコードからのサンプルコード

  private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
4

1 に答える 1

9

によって生成される警告を抑制するためにあり(E) elementData[lastRet = i]ます。これは、コンパイラにとってタイプが安全ではありません。コンパイラーは、実行時にキャストが成功することを保証できません。

しかし、コードを書いた人はそれが常に安全であると知っていたので@SuppressWarnings("unchecked")、コンパイル時の警告を抑制するために使用することにしました。

Ecplise IDEでコードがすっきりと見えるので、安全であると確信しているときに主に使用します。

于 2012-10-21T02:11:13.153 に答える