copyonwritearraylist strange error

1.3k Views Asked by At

I have this code:

int rnd1=Rnd.get(players.size());
int rnd2=Rnd.get(players.size());

while(rnd2==rnd1)
    rnd2=Rnd.get(players.size());


for(L2PcInstance player : players)
{
    if(player != players.get(rnd1) && player != players.get(rnd2))
           players.remove(player);
}

And I have this error:

Exception in thread "GeneralSTPool-8" java.lang.ArrayIndexOutOfBoundsException: 2 at java.util.concurrent.CopyOnWriteArrayList.get(Unknown Source) at java.util.concurrent.CopyOnWriteArrayList.get(Unknown Source) at net.sf.l2j.gameserver.model.RandomFight.pickPlayers(RandomFight.java:89) at net.sf.l2j.gameserver.model.RandomFight$pickPlayers.run(RandomFight.java:270) at net.sf.l2j.gameserver.ThreadPoolManager$RunnableWrapper.run(ThreadPoolManager.java:85) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)

What is going on here? Line 89 is this : for(L2PcInstance player : players). This shouldn't appeared since rnd.get() is from 0 to players.size() - 1.

1

There are 1 best solutions below

0
On

The intent seems to remove all but the two selected players from the list. There are simpler ways to do it. For example:

players.retainAll(Arrays.asList(players.get(rnd1), players.get(rnd2));

This also does not have problems with concurrent modifications, in case that was the reason you use CopyOnWriteArrayList.

The reason for the error, as already said in comments was: the player indices are generated on an initial list, and at that point they are indeed valid. The removal loop, however decreases the list size, and the previously generated indices can end outside the valid range.