【问题标题】:what can we benefit from using "@SuppressWarnings("unchecked")" in java?在 java 中使用“@SuppressWarnings("unchecked")”有什么好处?
【发布时间】:2012-10-11 06:04:20
【问题描述】:

当我阅读 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();
        }
    }

【问题讨论】:

标签: java arraylist annotations iterator


【解决方案1】:

它可以抑制(E) elementData[lastRet = i] 生成的警告,这对于编译器来说是类型不安全的。编译器无法保证强制转换在运行时会成功。

但由于编写代码的人知道它总是安全的,所以决定使用@SuppressWarnings("unchecked") 来抑制编译时的警告。

当我确定它会安全时,我主要使用它,因为它使我的代码在我的 Ecpise IDE 上看起来更干净。

【讨论】:

    猜你喜欢
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多