2012-10-21 29 views
3

当我阅读jdk源代码时,我找到了注释,但我不确定它为什么在这里使用?
在java中使用“@SuppressWarnings(”unchecked“)”会有什么好处?
我们应该什么时候使用它,为什么?从JDK源代码
示例代码
在java中使用“@SuppressWarnings(”unchecked“)”会有什么好处?

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(); 
     } 
    } 
+1

[Java中SuppressWarnings(“unchecked”)是什么意思?](http://stackoverflow.com/questions/1129795/what-is-suppresswarnings-unchecked-in-java) – LisaMM

回答

9

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

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

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

相关问题