Detailed collection-Iterator interface

Iterator interface

What is an iterator?

Iterator is an object, and its job is to traverse and select objects in the sequence. It provides a way to access various elements in a container object without having to expose the internal details of the object. With iterators, developers can traverse the container without knowing the underlying structure of the container. Because of the low cost of creating iterators, iterators are often referred to as lightweight containers.

Java Iterator (iterator) is not a collection, it is a method for accessing a collection, which can be used to iterate collections such as ArrayList and HasSet.

Insert picture description here

Two core methods of the Iterator interface:

  • boolean hasNext(): Judge whether there are any more elements, if there are more elements, return true.
  • E next(): return the next element of the iteration, if no element can be obtained, return NOSuchElementException

Get an iterator. If
you want to get an iterator, you can use the iterator() method.

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

public class RunoobTest {
    
    
    public static void main(String[] args) {
    
    

        // 创建集合
        ArrayList<String> sites = new ArrayList<String>();
        sites.add("Google");
        sites.add("Runoob");
        sites.add("Taobao");
        sites.add("Zhihu");

        // 获取迭代器
        Iterator<String> it = sites.iterator();
        while (it.hasNext()) {
    
    
            String ele = it.next();
            System.out.println(ele);
        }
    }
}

Other methods:

  • void remove(): Remove the last element returned by the iterator from the set specified by the iterator.
// 引入 ArrayList 和 Iterator 类
import java.util.ArrayList;
import java.util.Iterator;

public class RunoobTest {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(12);
        numbers.add(8);
        numbers.add(2);
        numbers.add(23);
        Iterator<Integer> it = numbers.iterator();
        while(it.hasNext()) {
    
    
            Integer i = it.next();
            if(i < 10) {
    
      
                it.remove();  // 删除小于 10 的元素
            }
        }
        System.out.println(numbers);
    }
}

Guess you like

Origin blog.csdn.net/qq_44346427/article/details/110729373