Using the iterator over the same set more than onc

2020-04-11 23:42发布

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

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

well, first I want to go through every object in the set and make a change to each object I visit. So I use:

while(it.hasNext()) {
        _someObject_ = it.next();
        _someObject_.add3();       //made up method
    }

Now that I've done this, I decide I want to iterate through the entire set from start to finish once more to carry out another method on them, given that I've just made changes to each element through my first iteration.

Can I just use

while(it.hasNext())

again?

I thought maybe the iterator has a pointer so once it's reached the last element on the first run through, if I call while(it.hasNext()) again, the pointer would still be at the end of the set, meaning my second while loop would be pointless.

标签: java
6条回答
男人必须洒脱
2楼-- · 2020-04-12 00:22

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.

查看更多
家丑人穷心不美
3楼-- · 2020-04-12 00:32

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.

查看更多
干净又极端
4楼-- · 2020-04-12 00:43

Iterators are single use only.

查看更多
三岁会撩人
5楼-- · 2020-04-12 00:44

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

查看更多
孤傲高冷的网名
6楼-- · 2020-04-12 00:45

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

查看更多
迷人小祖宗
7楼-- · 2020-04-12 00:47

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.

查看更多
登录 后发表回答