Java ListIterator(迭代器)

  LIstIterator是一個更增強大的Iterator的子類型,它只能用於各類List類的訪問,儘管Iterator只能向前移動,可是ListIterator能夠雙向移動,它還能夠產生相對於迭代器在列表指向的當前位置的前一個和後一個元素的索引,而且能夠使用set()方法替換它訪問過的最後一個元素. 你能夠經過ListIterator()方法產生一個指向List開始處的ListIteraor,而且還能夠經過調用ListIterator(n)方法建立一個一開始就指向索引列表n的元素處的ListIteratorjava

package java.util;

public interface ListIterator<E> extends Iterator<E> {
    boolean hasNext();     //檢查是否有下一個元素
    E next();              //返回下一個元素
    boolean hasPrevious(); //check是否有previous(前一個)element(元素)
    E previous();          //返回previous element
    int nextIndex();       //返回下一element的Index
    int previousIndex();   //返回當前元素的Index
    void remove();         //移除一個elment
    void set(E e);         //set()方法替換訪問過的最後一個元素 注意用set設置的是List列表的原始值
    void add(E e);         //添加一個element
}

,下面示例演示了這些能力:dom

//: holding/ListIteration.java
package object;
import typeinfo.pets.*;
import java.util.*;

public class ListIteration {
  public static void main(String[] args) {
    List<Pet> pets = Pets.arrayList(8);
    ListIterator<Pet> it = pets.listIterator();
    while(it.hasNext())
      System.out.print(it.next() + ", " + it.nextIndex() +
        ", " + it.previousIndex() + "; ");
    System.out.println();
    // Backwards:
    while(it.hasPrevious())
      System.out.print(it.previous().id() + " ");
    System.out.println();
    System.out.println(pets);    
    it = pets.listIterator(3);
    while(it.hasNext()) {
      it.next();
      it.set(Pets.randomPet());
    }
    System.out.println(pets);
  }
} /* Output:
Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7;
7 6 5 4 3 2 1 0
[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx]
[Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, EgyptianMau]
*///:~

 若是想直接反序輸出能夠這樣spa

package object;

import java.util.*;
public class ListInteger{ 
    static void reverse(List<Integer> list) {  
        ListIterator<Integer> fwd = list.listIterator();  
        ListIterator<Integer> rev =  
                list.listIterator(list.size()); //這裏將rev指向了List的最後一個元素
        int mid = list.size() >> 1;
        for(int i = 0; i < mid; i++) {  
            Integer tmp = fwd.next();  
            fwd.set(rev.previous());  
            rev.set(tmp);     }   
        } 
    public static void main(String[] args) { 
        List<Integer> src =     
                Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);  
        List<Integer> dest = new LinkedList<Integer>(src); 
        System.out.println("source: " + src);    
        System.out.println("destination: " + dest); 
        reverse(dest);  
        System.out.println("source: " + src);  
        System.out.println("destination: " + dest);  
        } 
}/* output:
source: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
destination: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
source: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
destination: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
*/
相關文章
相關標籤/搜索