I was just wondering what the easiest way to iterate over a set indefinitely, i.e. when it reaches the end it next();
calls the first object. I'm assuming that this is not an already predefined function in Java, so just looking for the easiest way to implement this in Java.
views:
308answers:
6If you're making the iterator, in the next method you can have an if condition that checks if there's another object in the list. If there is, then you return that object, if there isn't then you go back to the start of the list and return that object.
So you just want to loop over a data set for ever?
Can't you do something like this
for(int i =0; i < List.size() ; i++){
if(i == List.size()){
i =0;
}
}
This is what I can think of...
iterator = set.getIterator
//other code
if (iterator.hasNext())
//do code here
else
iterator = set.getIterator();
There's a method in the excellent Google Collections library which does this:
Set<String> names = ...;
Iterable<String> infinite = Iterables.cycle(names);
(I can't recommend the Google Collections library strongly enough. It rocks very hard. I'm biased as I work for Google, but I think pretty much every Googler writing Java would tell you how useful the collections are.)
Iterator it = mylist.iterator();
while (it.hasNext())
{
MyType t = (MyType)it.next();
// do something
if (!it.hasNext())
it = mylist.iterator();
}
I think what you want never help You can do anything with your iterator that's easy but you must be carefull with any new thing you add im not used with this style but this is what you want though :
if (! It.hasNext() ) { while ( It.hasPrevious() ) { It = It.Previous(); } } else { It = It.Next(); }
This way is nothing if your really interested you should instead make next pointer of the last to the first always when pushing a new list.