Shuffling a list in Java

Ditulis oleh: -
I had a list of words which I wanted to shuffle in random order. When I tried swapping random elements of the list, I needed two random numbers and ensure they are not equal. Was taking a lot of time.

But here is a better way
 private ArrayList shuffleWordList(ArrayList wrdList) {  
ArrayList lst = new ArrayList();
ArrayList tempList = (ArrayList) wrdList.clone();
int sz = wrdList.size();
for (int i = 0; i < sz; i++) {
int listSize = tempList.size();
int n = random.nextInt(listSize);
lst.add(tempList.get(n));//fill random word into new list
tempList.remove(n);//remove selected word
}
return lst;
}



What we are doing here is,
  •  Copy the list into a temporary list - tempList
  •  Create another empty list- lst
  •  Select one random word from temporary list
  •  Add this word to new list
  •  Remove the word from temporary list
       Repeat the steps n number of times