Introduction and use of Java collection iterator

 Iterators

       Iterators do not rely on indexes when traversing collections

        Java Iterator (Iterator) is a mechanism in the Java collection framework that provides a way to traverse collection elements without exposing the internal implementation of the collection. Java Iterator (iterator) is not a collection, it is a method for accessing collections, which can be used to iterate collections such as ArrayList and HashSet

  • get iterator object

    • Iterator<类型> it=list.iterator();

  • iterator method

    • it.hasNext(); Judgment check whether there is next element in the iterator, if there is, return true, if not, return false

    • in.next(); returns the element at the position pointed by the current pointer, and makes the pointer point to the next element

    • it. remove(). Use the iterator's delete method. The delete method of the collection cannot be used.

  • Walk through the points of attention

    • After the iterator has traversed all the elements, calling the next() method to forcibly obtain the elements again will cause NoSuchElementException.

    • After the iterator traversal is complete, the pointer is not reset.

    • Make sure to use the next() method once during each cycle, eg: call it multiple times, the iterator will skip some elements, resulting in incomplete traversal.

    • Collection methods cannot be used to add or delete while the iterator is traversing. eg: Use two variables to record the number of times of modification and the number of times expected to be modified respectively. When the iterator method is called, the two values ​​will change at the same time, but when the collection method is called, only the number of modifications will be changed.

    • Enhanced for loop : Java provides enhanced for loop (also known as foreach loop), which can easily traverse the elements in the collection. When using the enhanced for loop, there is no need to explicitly use the iterator, the compiler will automatically handle the creation and traversal of the iterator.

  • code example
public class IteratorExample {
    public static void main(String[] args) {
        // 创建一个包含整数的集合
        List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);

        // 获取迭代器对象
        Iterator<Integer> iterator = numbers.iterator();

        // 使用迭代器遍历集合
        while (iterator.hasNext()) {//判断迭代器内是否还有没被遍历的元素
            int number = iterator.next();//获取下一个元素
            System.out.println(number);

            // 使用迭代器的remove()方法删除元素
            if (number % 2 == 0) {
                iterator.remove(); //注意要用迭代器自带的删除方法!!!
            }
        }

        // 输出修改后的集合
        System.out.println(numbers);
    }
}
  • ListIterator (ListIterator) has one more addition method than ordinary iterators, which can add elements during traversal

public class ListIteratorExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("A");
        list.add("B");
        list.add("C");

        ListIterator<String> iterator = list.listIterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            if (element.equals("B")) {
                iterator.add("D");
            }
        }
        System.out.println(list);
    }
}
//在这个例子中,我们创建了一个包含三个元素的ArrayList。然后,我们使用ListIterator遍历列表,
//并在元素“B”之后添加一个新元素“D”。最后,我们打印出修改后的列表,它包含四个元素“A”、“B”、“D”和“C”。

Guess you like

Origin blog.csdn.net/qq_64680177/article/details/132128184