Java Iterator (Iterator)

Java Iterator (iterator) is not a collection, it is a method for accessing collections, and can be used to iterate collections such as ArrayList and HashSet.
Iterator is the simplest implementation of Java iterators. ListIterator is an interface in the Collection API, which extends the Iterator interface.
The two basic operations of iterator it are next, hasNext, and remove.

  • Calling it.next() will return the next element of the iterator and update the state of the iterator.
  • Call it.hasNext() to check if there are any elements in the collection.
  • Call it.remove() to delete the elements returned by the iterator.
import java.util.ArrayList;
import java.util.Iterator;

public class IteratorJava {
    
    
    public static void main(String[] args) {
    
    
        // 创建集合
        ArrayList<String> classes = new ArrayList<String>();
        classes.add("1年级");
        classes.add("2年级");
        classes.add("3年级");
        classes.add("4年级");

        // 获取迭代器
        Iterator<String> it = classes.iterator();

        // 输出集合中的元素
        for (; it.hasNext();) {
    
    
            System.out.println(it.next());
        }
    }
}

Guess you like

Origin blog.csdn.net/wjl__ai__/article/details/112390701