The same Iterator can only be traversed once

When I was learning today, when I encountered an iterator to traverse the collection, there was no element output. After thinking about it for a long time, I realized that "the same iterator can only be traversed once. If two traversals are written, the second traversal cannot Output"

The reason for my problem is "I want to delete an element in the collection and then traverse the output, but the output result is still not deleted before"

public void test5(){
    
    
        /*
        迭代器当中的 remove方法
         */
        Collection collection=new ArrayList();
        collection.add(1234);
        collection.add(new String("123"));
        collection.add(new Person(18,"Jerry"));
        Iterator iterator = collection.iterator();

        while (iterator.hasNext()){
    
    
            Object next = iterator.next();//next() 方法返回的是下一个对象
            if (next.equals("123")){
    
    
                iterator.remove();
            }
            System.out.println(next+"***");
        }

        while (iterator.hasNext()){
    
    
            System.out.println(iterator.next()+"$$$$");
        }

    }
运行结果	:这就说明下一个迭代器根本没执行
1234***
123***
Person{age=18, name='Jerry'}***

After reading the information, I figured out that the same iterator can only be traversed once, so I created another iterator to solve the problem

  public void test5(){
    
    
        /*
        迭代器当中的 remove方法
         */
        Collection collection=new ArrayList();
        collection.add(1234);
        collection.add(new String("123"));
        collection.add(new Person(18,"Jerry"));
        Iterator iterator = collection.iterator();

        while (iterator.hasNext()){
    
    
            Object next = iterator.next();//next() 方法返回的是下一个对象
            if (next.equals("123")){
    
    
             iterator.remove();
           }
            System.out.println(next+"***");
        }
        Iterator iterator1 = collection.iterator();
        while (iterator1.hasNext()){
    
    
            System.out.println(iterator1.next()+"$$$$");
        }
    }
修改后的运行结果:正常遍历输出了 
1234***
123***
Person{age=18, name='Jerry'}***
1234$$$$
Person{age=18, name='Jerry'}$$$$

Summary: The process of solving problems is painful, but successful solutions make people really happy! ! !

Guess you like

Origin blog.csdn.net/weixin_46351306/article/details/113705527