3

Java知识点总结(Java容器-Iterator)

@(Java知识点总结)[Java, Java容器]

Iterator

Iterator对象称作迭代器,用于方便地实现对容器内元素的遍历操作
Iterator接口定义如下:

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

苏生
803 声望725 粉丝