Java array shuffling

I noticed that the base int array changes according to how the list is created:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;


public class Shuffling {

    static Integer[] intArr = {1, 2, 3, 4, 5};
    static Random random = new Random(7);
    public static void main(String[] args) {

        List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArr));
        Collections.shuffle(intList, random);
        System.out.println("List after shuffling: " + intList);
        System.out.println("intArr: " + Arrays.toString(intArr));
        //OUTPUT:
        //List after shuffling: [5, 4, 1, 3, 2]
        //intArr: [1, 2, 3, 4, 5]


        List<Integer> intList2 = Arrays.asList(intArr);
        Collections.shuffle(intList2, random);
        System.out.println("List2 after shuffling: " + intList2);
        System.out.println("intArr: " + Arrays.toString(intArr));
        //OUTPUT:
        //List2 after shuffling: [5, 3, 4, 2, 1]
        //intArr: [5, 3, 4, 2, 1]
    }
}

Why is this happening?

+5
source share
5 answers

Arrays.asList() creates a special list that is supported by the original array.

That is why the list is not supported (optional) add()and remove()from the interface Collection (they would not have been possible with the use of the array).

Interestingly, the returned class is called ArrayList, although it should not be confused with java.util.ArrayList.

System.out.println(
    Arrays.asList("1", "2", "3")
    .getClass().getName()
);
// Output: java.util.Arrays$ArrayList
+8
source

From javadoc to Arrays.asList(T... a):

, . ( "write through" .)

+3

API :

public static <T> List<T> asList(T... a)

, . ( "write through" .)

, , intList2, intArr. ArrayList , , intList, intArr ( )

+2
List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArr));

intList . , , , . ( . ).

List<Integer> intList2 = Arrays.asList(intArr);

intList2 . . , intList2, intArr.

+1

The actual change occurs in a random seed passed to the shuffle method. Each time the shuffle method is called, it gets the next, sic different, number in from the Random instance.

0
source

All Articles