Using the iterator over the same set more than once in java

后端 未结 6 1028
耶瑟儿~
耶瑟儿~ 2021-01-13 20:08

Say I\'m iterating over a set in java, e.g.

Iterator<_someObject_> it = _someObject_.iterator();

well, first I want to go through eve

相关标签:
6条回答
  • 2021-01-13 20:16

    Iterators are single use only.

    0 讨论(0)
  • 2021-01-13 20:19

    As I guess you've discovered Iterator has no "reset" method... so you just grab ANOTHER Iterator. Simple.

    0 讨论(0)
  • 2021-01-13 20:21

    No, you can not do this. Just ask the Iterable object for another iterator.

    0 讨论(0)
  • 2021-01-13 20:22

    It's true that iterators are single use only, but there is a class called ListIterator that allows you to do this by looking back on the list. An example would be:

    ArrayList<String> list = new ArrayList<String>();
    list.add("hey!");
    list.add("how");
    list.add("are");
    list.add("you?");
    ListIterator it = list.listIterator();
    while(it.hasNext()){
       System.out.println(it.next() +" ");//you print all the elements
    }
    //Now you go back. You can encapsulate this while sentence into a void reset method.
    while(it.hasPrevious()){
       it.previous();
    }
    //Now you check that you've reached the beginning of the list
    while(it.hasNext()){
       System.out.println("back " + it.next() +" ");//you print all the elements
    }
    

    I think it could be useful for you that class.

    0 讨论(0)
  • 2021-01-13 20:35

    Sorry, but the contract of an Iterator states that you can only go through it once.

    Given that you can't know for sure the order of the next Iterator, or even the content for that matter (it might change!), you're better off doing all the modifications or method calls in the same block.

    0 讨论(0)
  • 2021-01-13 20:35

    it.hasNext() is false after the loop, this is exactly why the while loop ends. If you do another while(it.hasNext()) afterwards it.hasNext() will still be false so this loop will exit immediately. You need a new iterator for your new loop.

    0 讨论(0)
提交回复
热议问题