java Iterator和ListIterator

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Iterator和ListIterator相关的知识,希望对你有一定的参考价值。

package me.illuminatiproductions;

import java.util.*;

public class Main {

    public static void main(String[] args) {

        //Iterators
        ArrayList<String> names = new ArrayList<>();
        names.add("Noah");
        names.add("Kody");
        names.add("Damascus");
        names.add("Lars");
        names.add("Nadie");

        //Loop through a collection with an iterator
        Iterator<String> nameIterator = names.iterator();
        System.out.println("Here's all of the names: ");
        while(nameIterator.hasNext()){ //loop while there is another element ahead
            System.out.println(nameIterator.next()); //returns and moves to next element
        }

        //Use a listIterator when working with list type collections
        ListIterator<String> nameListIterator = names.listIterator();
        System.out.println("Names: ");
        while(nameListIterator.hasNext()){
            System.out.println(nameListIterator.next());
        }

        //Now, make it go backwards
        System.out.println("Names backwards: ");
        while(nameListIterator.hasPrevious()){
            System.out.println(nameListIterator.previous());
        }

        //iterator with hashmaps
        HashMap<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");

        Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pair = it.next();
            System.out.println(pair.getKey() + " = " + pair.getValue());
        }

    }
}

以上是关于java Iterator和ListIterator的主要内容,如果未能解决你的问题,请参考以下文章

java iterator方法

请问java中的Iterator和Iterable有些啥区别啊?

Java 集合系列18之 Iterator和Enumeration比较

关于Enumeration和Iterator的区别.

Java复习之-Iterator

Java中的集合(十五) Iterator 和 ListIteratorEnumeration