Iterator

  • Post author:
  • Post category:其他


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

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<String> arrayList = new ArrayList<String>();

        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<String> iterator = arrayList.iterator();
        while (iterator.hasNext()){
            String element = iterator.next();
            System.out.print(element +" ");
        }
        System.out.println();

        //Modify objects being iterated
        ListIterator<String> 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();

    }
}



版权声明:本文为qq_38360675原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。