Reputation: 1557
I'm making a game using Libgdx. In my main loop, I use an iterator to iterate through all the elements of my world. My World
class look like this :
public class World implements Iterable<GameElement>
{
...
public Iterator<GameElement> iterator()
{
return listGameElements.iterator();
}
}
But when I profile my application, there is a lot of allocations coming from the line listGameElements.iterator()
(this line is called at every game loop, so a lot of times in a second).
I wanted to put my iterator as an private attribute of my class, but the iterator can be used only one time. Is there a way to rewind an iterator, to avoid making more allocations?
Upvotes: 1
Views: 2042
Reputation: 13657
You can do it based on the ListIterator it allows you to go in both directions.
Example of usage:
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
ListIterator listIterator = aList.listIterator();
System.out.println("moving forward");
while(listIterator.hasNext()) {
System.out.println(listIterator.next());
}
System.out.println("moving backward");
while(listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
Upvotes: 4