I have created simple shuffle method everyting seems okay but there is a problem which i can't find.

Here is my Code Below:

public static <E> void shuffle(List<? extends E> list) {
    List<E> temp = new ArrayList<>();

    while (list.size() != 0) {
        E val = list.remove((int) (Math.random() * list.size()));
        temp.add(val);
        System.out.println(val);
    }
    System.out.println(temp);

    list = temp;
}

This is the test case:

ArrayList<Integer> arr = new ArrayList<>();
    arr.add(1);
    arr.add(2);
    arr.add(3);
    arr.add(4);
    arr.add(5);
    arr.add(6);
    System.out.println(arr);

    shuffle(arr);

    System.out.println("-->" + arr);

The problem is last print out method shows that arr is empty --> [] It Should be something like that [4,3,1,2,6,5]
Problem could be this line but i did not understand why ?

 --> list = temp;
有帮助吗?

解决方案

Yes, it's this line:

list = temp;

All that does is copy the temp reference to the list reference. Now, both list and temp refer to your local list originally referred to by temp.

You'll want to add the contents of temp back to list instead.

list.addAll(temp);

其他提示

list = temp just assigns a new value (the contents of temp) to the local variable named list - it does not change the object that list originally pointed to.

If you want to achieve such functionality, you could just re-add all the items in temp to list (after the while loop concludes, so you know it's empty):

list.addAll(temp);

The shuffle method receives a copy of a reference to your list. When you do list = temp; you're telling that reference to point to temp.

So you basically empty the list that is passed to the method and then you lose access to it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top