If you use Java Iterator, you fall into an infinite loop.

Asked 2 years ago, Updated 2 years ago, 98 views

If you do it like this, it's printed indefinitely. What's wrong with this? I don't understand the exact purpose of Iteratoriter = set1.iterator();

import java.util.*;
public class Generic1 {
    public static void main(String[] args){

        Set<String> set1 = new HashSet<>();
        boolean yesorno = set1.add("dada");
        set1.add("dsafd");
        set1.add("dfdsa");
        set1.add("dfds");

        System.out.println(yesorno);
        System.out.println(set1.size());





        while(set1.iterator().hasNext()){
            String str = set1.iterator().next();
            System.out.println(str);
        }



    }
}

Tryhelloworld's http://tryhelloworld.co.kr/questions/1038 I was trying to answer the question, but I thought it would be nice to share it with you, so I'm moving it here.

java iterator tryhelloworld

2022-09-21 15:39

1 Answers

Set1.iterator() creates a new iterator every time. The output statement of iter1 == ether2 in the code below is not executed. This is because iter1 and iter2 are newly created emitters. So if you want to use hasNext, you shouldn't use the e-interator that you got from the set1.iterator() every time, but you have to make one as shown below and keep using it.

import java.util.*;

class CodeRunner{
    public static void main(String[] args){

        Set<String> set1 = new HashSet<>();
        set1.add("dada");
        set1.add("dsafd");
        set1.add("dfds");

        Iterator<String> iter1 = set1.iterator();
        Iterator<String> iter2 = set1.iterator();
        if(iter1==iter2){
            System.out.println("SameIterator");
        }

        while(iter1.hasNext()){
            String str = iter1.next();
            System.out.println(str);
        }

        // while(set1.iterator().hasNext(){//set1.iterator() is always true because it is a new iterator.
        //     //     String str = set1.iterator().next();
        //     //     System.out.println(str);
        // }
    }
}


2022-09-21 15:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.