Java 迭代器

迭代器(iterator)有時又稱遊標(cursor)是程序設計的軟件設計模式,可在容器(container,例如鏈表陣列)上遍訪的接口,設計人員無需關心容器的內容。html

1.Iterator是一個接口,它實現瞭如何使用迭代器,代碼以下java

package java.util;  

public interface Iterator<E> {  

    boolean hasNext();  

    E next();  

    void remove();  

}  

hasNext() :遍歷過程當中,斷定是否還有下一個元素。(從Collection對象的第一個元素開始)設計模式

next() : 遍歷該元素。(即取出下一個元素)api

remove(): 移除剛剛遍歷過的元素。數組

2.Iterable也是一個接口,它實現了返回一個迭代器,代碼以下oracle

package java.lang;

import java.util.Iterator;

public interface Iterable<T> {

    Iterator<T> iterator();

}

Collection接口拓展了接口Iterable,根據以上的對Iterable接口的定義能夠發現,其要求實現其的類都提供一個返回迭代器Iterator<T>對象的方法。spa

3.切記,對JAVA集合進行遍歷刪除時務必要用迭代器設計

package wm_collection;

import java.util.*;

public class test {

public static void main(String[] args) {

//使用了泛型

List<String> list=new ArrayList<String>();

list.add("e");

list.add("r");

        int i;

Iterator it= list.iterator();

//調用Iterator

while(it.hasNext()){

String string=(String) it.next();

if(string.equals("e"))

{

it.remove();

}

}

Iterator i1= list.iterator();

while(i1.hasNext()){

System.out.println("a");

System.out.println(i1.next());

}

/*for(i=0;i<list.size();i++){

System.out.println(list.get(i));

}*/

/*for(String str:list){ 

        System.out.println(str);  

      }  

}*/}

}

由於在循環語句彙總刪除集合中的某個元素,就要用迭代器iterator的remove()方法,由於它的remove()方法不只會刪除元素,還會維護一個標誌,用來記錄目前是否是能夠刪除狀態,如調用以前至少有一次next()方法的調用。code

4.for each與Iteratorhtm

for each是jdk5.0新增長的一個循環結構,能夠用來處理集合中的每一個元素而不用考慮集合定下標。
格式以下 
for(variable:collection){ statement; }
定義一個變量用於暫存集合中的每個元素,並執行相應的語句(塊)。collection必須是一個數組或者是一個實現了lterable接口的類對象。 

相關文章
相關標籤/搜索