and*_*qee 3 java iterator annotations arraylist
当我读取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();
}
}
Run Code Online (Sandbox Code Playgroud)
它是为了抑制生成的警告(E) elementData[lastRet = i],对于编译器类型是不安全的.编译器无法确保转换在运行时成功.
但是,由于编写代码的人知道它总是安全的,所以决定@SuppressWarnings("unchecked")在编译时使用来抑制警告.
我主要是在确定它是安全的时候使用它,因为它使我的代码在我的Ecplise IDE上看起来更干净.
| 归档时间: |
|
| 查看次数: |
6899 次 |
| 最近记录: |