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?
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With