views:

308

answers:

6

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.

+1  A: 

If 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.

indyK1ng
I understand you posted your answer before mine, but as seen in my answer that is what I am basically doing right now, I was just wondering if there was a better way than instantiating a new Iterator object every time I get to the end
Soldier.moth
A: 

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;
 }

}
PSU_Kardi
if I wanted to create an infinite loop then yes, but I was more concerned with getting/creating an iterator where I don't have to worry about checking if hasNext() == false , but that whenever I call Next() it will return the next element as if the front of the list was attached to the end of the list to make a neat little circle of objects
Soldier.moth
if i == list.size() then you are already outside of the for loop and your code would do nothing. Also you can't use List.size(), it's not a static method.
AlexC
A: 

This is what I can think of...

iterator = set.getIterator
//other code
if (iterator.hasNext())
    //do code here
else
    iterator = set.getIterator();
Soldier.moth
That too seems okay
+14  A: 

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.)

Jon Skeet
+1 for Iterables.cycle
coobird
+1  A: 
Iterator it = mylist.iterator();
while (it.hasNext())
{
  MyType t = (MyType)it.next();

  // do something

  if (!it.hasNext())
    it = mylist.iterator();
}
AlexC
A: 

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.

Malid