AVAでのIterator
3364 ワード
(Iterator pattern)
、
Java 。 JDK java collection :
Iterator it = list.iterator();
while(it.hasNext()){
//using “it.next();”do some businesss logic
}
。
、
(Iterator) , (Cursor) 。GOF : (container) , 。
, 。 , 。 ; , 。 。
, , “ ” ( 、 ), ; , 。 , 。
, 。 。
:
1) (Iterator): 。
2) (Concrete Iterator): , 。
3) (Container): 。
4) (Concrete Container): —— 。
:
, 。 , , “ ”。
, , —— 。 , , , 。 。
、
, 。 , 。 , 。
1. , 。 Java collection , , ; , 。 、 , java , 。
2. 。 。 , 。 —— , java 。
。 。 。
Java Collection , 。 。 , 。
, Java Collection 。
// ,
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
// , List 。 ,
// , List ArrayList 。
// , 。AbstractList 。
public abstract class AbstractList extends AbstractCollection implements List {
……
//
public Iterator iterator() {
return new Itr();
}
//
private class Itr implements Iterator {
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public Object next() {
checkForComodification();
try {
Object next = get(cursor);
lastRet = cursor++;
return next;
} catch(IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch(IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
。 , , 。 ……
、
, 。 :
, ?
, ?
, , 。
、
, :
1) 。 , 。
2) 。 java Collection , 。
3) , 。 。
:
1) 。
2) 。
3) ( )。