Wechat search “Java fish”, a knowledge point every day not bad

(1) One knowledge point every day

Do you know what an Iterator is?

(2) Answer

The iterator pattern is one of twenty-three design patterns for sequential access to the elements of a collection object without knowing the underlying representation of the collection object.

In Java, iterator.hasnext () checks for the existence of the next record, iterator.next iterates through the elements of the collection.

For the implementation of iterators, see the following figure:

Based on the above figure, the use of iterators can be divided into the following four steps:

The collection returns an iterator using the iterator() method, which points to the element before the first element before next.

2. Call the hasNext method to see if there are any more elements.

3. Execute the next() method to move the pointer down to the next element in the collection.

Some notes about iterators:

When iterators are used, iterator is used instead of list to delete elements. Take this code for example:

@Test
public void testMethod(a){
    List list=new ArrayList();
    list.add("1");
    list.add("2");
    list.add("3");
    Iterator iterator=list.iterator();
    while (iterator.hasNext()){
        String object = (String) iterator.next();
        if ("3".equals(object)){
            list.remove(object);
        }
    }
    System.out.println(list);
}
Copy the code

This code using the list to delete “3” this element, the results will be reported to the ConcurrentModificationException errors

This error is caused by the need to read the collection source, here is not to do more extension, the correct deletion method is as follows:

//list.remove(object); error
iterator.remove();
Copy the code