Iterator

使用迭代器遍历集合的内容:

1.通过调用集合的Iterator()方法,获取指向集合开头的迭代器。

2.建立一个hasNext()方法调用循环。只要hasNext()方法返回true,就继续迭代。

3.在循环中,通过调用next()方法获取每个元素。

package Collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

/**
 * @author 犀角
 * @date 2019/11/2 9:49
 * @description 使用迭代器遍历集合的内容
 */
public class IteratorDemo {
    public static void main(String[] args) {
        //create an Array list
        ArrayList arrayList = new ArrayList();

        arrayList.add("q");
        arrayList.add("e");
        arrayList.add("fg");
        arrayList.add("iu");
        arrayList.add("ug");

        //Use Iterator display contents of arraylist.
        System.out.println("Original contents of arraylist: ");
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()){
            String element = iterator.next();
            System.out.print(element +" ");
        }
        System.out.println();

        //Modify objects being iterated
        ListIterator lit = arrayList.listIterator();
        while (lit.hasNext()){
            String element = lit.next();
            lit.set(element + "+");
        }
        System.out.println("Modified contents of arraylist: ");
        iterator = arrayList.iterator();
        while (iterator.hasNext()){
            String element = iterator.next();
            System.out.print(element + " ");
        }
        System.out.println();

        //Now,display the list backwards.
        System.out.println("Modified list backwards: ");
        while (lit.hasPrevious()){
            String element = lit.previous();
            System.out.print(element + " ");
        }
        System.out.println();

    }
}

 

你可能感兴趣的:(Java)