Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java array shuffling

Tags:

java

arrays

I've noticed that the underlying int array is getting changed given the way the list is being 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 that happening?

like image 347
dimitrisli Avatar asked Dec 02 '10 12:12

dimitrisli


2 Answers

Arrays.asList() constructs a special list that is backed by the original array.

Which is why the list does not support the (optional) add() and remove() methods from the Collection interface (they wouldn't be possible using an array).

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

System.out.println(
    Arrays.asList("1", "2", "3")
    .getClass().getName()
);
// Output: java.util.Arrays$ArrayList
like image 111
Sean Patrick Floyd Avatar answered Oct 25 '22 13:10

Sean Patrick Floyd


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

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

like image 24
Armand Avatar answered Oct 25 '22 13:10

Armand