# Comparing two shuffling methods

I'm trying to randomly shuffle an collection of integers within a List and I have came up with two shuffling method that does the job. However, I'm not sure which one works better. Does any one have any comments or suggestions?

public class TheCollectionInterface {

public static <E> void swap(List<E> list1, int i, int j){
E temp = list1.get(i);
list1.set(i, list1.get(j));
list1.set(j, temp);
}

//alternative version
//    public static void shuffling(List<?> list, Random rnd){
//        for(int i = list.size(); i >= 1; i--){
//            swap(list, i - 1, rnd.nextInt(i));
//        }
//    }

public static <E> void shuffling(List<E> list1, Random rnd){
for(int i = list1.size(); i >= 1; i--){
swap(list1, i - 1, rnd.nextInt(list1.size()));
}
}

public static void main(String[] args) {

List<Integer> li2 = Arrays.asList(1,2,3,4,5,6,7,8,9);

Random r1 = new Random();

TheCollectionInterface.shuffling(li2, r1);

System.out.println(li2);
}
}

• Did you consider Collections.shuffle()? Mar 12, 2016 at 2:26
• yes, that's another alternative, but I just want to come up with a shuffling method myself, practice with the logic :)
– Thor
Mar 12, 2016 at 2:28

Your algorithm doesn't have simple uniform distribution over !n. Your alternative do has it, is actually a known algorithm named Fisher–Yates shuffle.