ArrayList实现了ListIterator接口
-
public interface ListIterator<E> extends Iterator<E> {
-
boolean hasNext();
-
E next();
-
boolean hasPrevious();
-
E previous();
-
int nextIndex();
-
int previousIndex();
-
void remove();
-
void set(E e);
-
void add(E e);
-
}
这个接口在Iterator接口的基础上,可以查找前驱和后继节点.还能添加和修改.
ArrayList的ListIterator实现.
-
private class ListItr extends Itr implements ListIterator<E> {
-
ListItr(int index) {
-
super();
-
cursor = index;
-
}
-
-
public boolean hasPrevious() {
-
return cursor != 0;
-
}
-
-
public int nextIndex() {
-
return cursor;
-
}
-
-
public int previousIndex() {
-
return cursor - 1;
-
}
-
-
@SuppressWarnings("unchecked")
-
public E previous() {
-
checkForComodification();
-
int i = cursor - 1;
-
if (i < 0)
-
throw new NoSuchElementException();
-
Object[] elementData = ArrayList.this.elementData;
-
if (i >= elementData.length)
-
throw new ConcurrentModificationException();
-
cursor = i;
-
return (E) elementData[lastRet = i];
-
}
-
-
public void set(E e) {
-
if (lastRet < 0)
-
throw new IllegalStateException();
-
checkForComodification();
-
-
try {
-
ArrayList.this.set(lastRet, e);
-
} catch (IndexOutOfBoundsException ex) {
-
throw new ConcurrentModificationException();
-
}
-
}
-
-
public void add(E e) {
-
checkForComodification();
-
-
try {
-
int i = cursor;
-
ArrayList.this.add(i, e);
-
cursor = i + 1;
-
lastRet = -1;
-
expectedModCount = modCount;
-
} catch (IndexOutOfBoundsException ex) {
-
throw new ConcurrentModificationException();
-
}
-
}
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2121743/
,如需转载,请注明出处,否则将追究法律责任。