JAVA Collection--Iterator Iterator

Iterator iterator overview

Collection inherits the Iterable interface and indirectly the Iterator interface to implement the traversal function of the collection.

Iterator interface provides methods

boolean hasNext()
returns true if there are still elements to iterate over.
Object next()
returns the next element of the iteration.
void remove()
deletes the element returned by the last next method of the collection
void forEachRemaining(Consumer action)
java8 new function, traverse the collection through lambda expression

case

    //1. Collectin 的子接口set|list |queue都可以这样使用(list为例)
    List collection = new LinkedList();
    Iterator iterator =collection.iterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
    }
    //2. list 集合实现了ListIterator接口也可以这样使用
    List collection = new LinkedList();
    ListIterator iterator =collection.ListIterator();
    //ListIterator iterator =collection.ListIterator(index);
    while(iterator.hasNext()){
        System.out.println(iterator.next());
    }
    //3.Map集合
    Map map = new TreeMap();
    //遍历值
    Collection collection =map.values() ;   
    Iterator iterator =collection.iterator();

    while(iterator.hasNext()){
        System.out.println(iterator.next());
    }
    //按键遍历
    Set keys =map.keySet();
    Iterator iterator =keys .iterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
    }

important point

1. The collection cannot be modified during traversal
2. To delete an element, it can only be deleted through the remove() method


    List list = new LinkedList();
    list.add(1);
    list.add(2);
    list.add(3);
    System.out.println(list);//输出: [1,2,3]

    ListIterator iterator =list.listIterator();

    while(iterator.hasNext()){
        iterator.next();// 必须调用 
        iterator.remove();
    }

    System.out.println(list);//输出: [1,2,3]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324603336&siteId=291194637