Ok, so I have an ArrayList (arrBok), which is full of book objects (the code is in Norwegian, so pay no attention to that please). I want to make a public method which iterates through all the objects in the `ArrayList’.
When I execute the code, it just seems to run in an infinite loop, not producing any return values.
Here is the relevant (I hope, because there are a couple of other classes involved) part of the code;
public String listAll()
{
itr = arrBok.iterator();
while (itr.hasNext())
{
i++;
}
return "lol";
}
This code does nothing useful, but I just want to see if it can iterate through it successfully.
What I have tried so far;
-
Tested if the
bokArr (ArrayList)is empty, which it’s not. It has 4 objects inside of it. -
Return the
toString()method of theitr, with the following result;
java.util.AbstractList$Itr@173a10f // <– not sure if this would be relevant to anything
return itr.next().toString();<– // which seems to return the first object in the array, does that make sense?
That code as quoted won’t compile, you’re missing a couple of declarations. But I think I get the gist.
hasNexttells you that the iterator has a next value, but doesn’t take you to it. To do that, you usenext. So that is an endless loop because you’re never callingnext.With any recent compiler, you can use the much simpler notation for this:
That iterates through the collection (list, in this case) for you.