What is the fastest way to change the order of elements in an ArrayList?

Viewed 66

I have a first ArrayList:

ArrayList<Move> moves = new ArrayList<>();

and want to reorder the elements randomly into a second one:

ArrayList<Move> randomMoves = new ArrayList<>();

Normally I do:

    while (randomMoves.size() < moves.size()) {
    
        int index = (int) (Math.random() * moves.size());

        while (randomMoves.contains(moves.get(index))) {

            index = (int) (Math.random() * moves.size());
        }
        
        randomMoves.add(moves.get(index));
    }

but it goes without saying that this is a performance disaster (the last elements will take time to get chosen randomly)...

normally this is not so much of an issue, but this code is going to be executed in a time-critical part of the application and I don't have a lot experience with time-critical code...

enlighten me :)

S.

1 Answers
Related