I heed to do some arraylist manipulations and I've run into a problem, creating an infinite loop. Can someone explain it why, please?
p.s. don't worry about trace command, I'm creating custom java extension to smartfoxserver 2x instance.
String deckOf4Array[] = new String[] {"AD","KD","QD","JD","10D","9D","8D","7D","6D","AH","KH","QH","JH","10H","9H","8H","7H","6H","AC","AS","KS"};
List<String> deckOf4List = new ArrayList<String>(Arrays.asList(deckOf4Array));
for(int n=0; n<4; n++)
{
int cardindex = new Random().nextInt(deckOf4List.size()-1);
trace("cardindex: " + cardindex);
for (ListIterator<String> iter = deckOf4List.listIterator(); iter.hasNext(); )
{
// Here goes infinite loop
trace("cardindex: " + cardindex);
if(cardindex == iter.nextIndex())
{
// Here goes manipulations
}
iter.remove();
}
}
You have to edit your for loop...
for (ListIterator<String> iter = deckOf4List.listIterator(); iter.hasNext(); iter.next())
The nextIndex() method returns the upcoming index, however, it does not move the cursor in your iteration. So if you put iter.next()
in your for-loop, it will actually move the cursor. In your case, you are not moving the cursor, so you keep iterating over index 0.
As for the official documentation...
next()
-
Returns the next element in the list and advances the cursor position.
int nextIndex()
-
Returns the index of the element that would be returned by a subsequent call to next().