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]开发者_JAVA百科
//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.)
To quote from the API link text:
public static <T> List<T> asList(T... a)
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
So, any changes you perform on intList2 will have an effect on intArr. The constructor of ArrayList on the other side, will copy the elements, so changes made to the order in intList will not affect intArr (because elements are copied)
List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArr));
In intList you got a shallow copy of your array. Shallow copy means, you copied only array itself, not elements it holds. (There is also a deep copy. It means a complete array copy).
List<Integer> intList2 = Arrays.asList(intArr);
In intList2 you got the same array. Not even a shallow copy. Whenever you change intList2, you also modify intArr.
The actual change is in the random seed being passed into the shuffle method. Every time the shuffle method is called it gets the next, sic different, number in from the Random instance.
精彩评论