Java知識點總結(Java容器-Iterator)

Java知識點總結(Java容器-Iterator)

@(Java知識點總結)[Java, Java容器]java

Iterator

Iterator對象稱做迭代器,用於方便地實現對容器內元素的遍歷操做
Iterator接口定義以下:this

  • boolean hasNext(); //判斷是否有元素沒有被遍歷
  • Object next(); //返回遊標當前位置的元素並將遊標移動到下一個位置
  • void remove(); //刪除遊標左面的元素,在執行完next以後該操做只能執行一次

clipboard.png

迭代器的使用

HashSet set = new HashSet();
set.add("1" );
set.add("2" );
set.add("3" );
/*Iterator it = set.iterator();
while (it.hasNext()) {
  String  obj = (String) it.next();
  System.out.println(obj);
}*/
for (Iterator it = set.iterator(); it.hasNext();) {
  String  obj  = (String) it.next();
  System.out.println(obj);      
}

Iterator實現

/**
 * Iterator實現原理
 */
private  class Itr implements Iterator<E> {
        int cursor = 0;  //遊標
        int lastRet = -1; //上一次遍歷元素的下標
 
public  boolean hasNext() {
            return cursor != size();
        }
        public E next() {
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
 
            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }
}
相關文章
相關標籤/搜索