十一、Java集和(三)——Iterator迭代器接口

1. Iterator迭代器接口

1)定義:

Iterator對象稱爲迭代器(設計模式的一種),主要用於遍歷 Collection 集合中的元素。

2) 使用:
Collection c1 = new ArrayList();
c1.add(123);//自動裝箱
c1.add(new Person("Tom",12));
c1.add(new String("AA"));
c1.add(new Date(234234324L));
c1.add("BB");
  • 獲取迭代器
Iterator iterator = c1.iterator();//獲取迭代器
  • 遍歷
方式一(搞笑的)
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.next());

System.out.println(iterator.next());//當所有的元素都next完之後,再next會報NoSuchElementException
方式二(不推薦)
for(int i = 0;i < c1.size();i++){
	System.out.println(iterator.next());
}
方式三(推薦)
hasNext():判斷集合的下個位置是否還有元素
while(iterator.hasNext()){
	//next():① 指針下移 ② 將下移以後位置上的元素返回
	Object obj = iterator.next();
	System.out.println(obj);
}
3)迭代器執行原理

迭代器執行原理

4)錯誤的遍歷寫法
Collection c1 = new ArrayList();
c1.add(123);//自動裝箱
c1.add(new Person("Tom",12));
c1.add(new String("AA"));
c1.add(new Date(234234324L));
c1.add("BB");
//錯誤方式一:
Iterator iterator = c1.iterator();
while(iterator.next() != null){
	System.out.println(iterator.next());
	
}
//錯誤方式二:每次調用iterator()時,都會返回一個迭代器對象,指針從頭開始
while(c1.iterator().hasNext()){
  	Object obj = c1.iterator().next();
	System.out.println(obj);
}
5)for-each循環的方式遍歷集和(增強for循環)
Collection c1 = new ArrayList();
c1.add(123);//自動裝箱
c1.add(new Person("Tom",12));
c1.add(new String("AA"));
c1.add(new Date(234234324L));
c1.add("BB");
//格式:for(集合元素類型  變量名 : 待遍歷的集合對象的引用)
for(Object obj : c1){
	System.out.println(obj);
}
遍歷數組
 @Test
public void test2(){
	int[] arr = {1,2,3,4,5};
	for(int i : arr){
		System.out.println(i);
	}
}

2. List集和特有Iterator

List接口提供了List特有的迭代器

List中的抽象方法
ListIterator<E> listIterator(int index);
ArrayList中實現的方法
public ListIterator<E> listIterator() {
    return new ListItr(0);
}

ListItr內部類: 可以通過ListItr在遍歷的同時,實現add和set操作,可以向前或向後遍歷

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();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章