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

后端 未结 6 1071
耶瑟儿~
耶瑟儿~ 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: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 list = new ArrayList();
    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.

提交回复
热议问题