About the problem that HashSet objects cannot be added or deleted using iterators

The generation of the problem:

Encountered a case when learning the HashSet class:

The King of Golden Horn has a purple gold gourd, which contains "Sun Xingzhe", "Xingzhe Sun", "Zhe Xing Sun". Now there is a "Sun Wukong", he said: First let out my friend "Sun Xingzhe", and then put me in.
Please use HashSet and Monkey classes to achieve the above requirements.

If you use iterators to add and delete operations as usual:

public static void main(String[] args) {
    
    
        Monkey m1 = new Monkey("孙行者");
        Monkey m2 = new Monkey("行者孙");
        Monkey m3 = new Monkey("者行孙");
        Monkey m = new Monkey("孙悟空");
        HashSet set = new HashSet();
        set.add(m1);
        set.add(m2);
        set.add(m3);
        System.out.print("现在紫金葫芦里有:");
        for (Object s : set) {
    
    
            System.out.print(s);
        }
        
        Iterator it = set.iterator();
        while (it.hasNext()){
    
    
            Object o = it.next(); // 此行运行报错!
            if (((Monkey)o).getName().equals("孙行者")){
    
    
                set.remove(o); // 在此处进行删除操作
                System.out.println("\n现在放出“孙行者”");
            }
        }
        
		System.out.println("现在放入“孙悟空”");
        set.add(m);

        System.out.print("\n现在紫金葫芦里有:");
        for (Object s : set) {
    
    
            System.out.print(s);
        }

An error will be reported, and the results are as follows:
Insert picture description here

The solution of the problem:

1. Theory

Later, I understood that the use of iterators is equivalent to the HashSet class object temporarily hosting its own elements to the iterator. So if you want to add and delete operations, you must also complete it through the iterator object. Looking at the source code, you can see that if you directly manipulate the HashSet class object in the iterator, it will cause the number of element modifications and the expected number of modifications to be different, and an error will be reported. Adding and deleting objects through iterators will not cause problems.

2. Practice

Change the above line of delete operation code:

// set.remove(o); 原代码
it.remove(); // 更改后

Normal operation, the results are as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/SoupTC/article/details/109398618