问题描述
为什么我的代码不起作用?
Why does my code not work?
package generatingInitialPopulation;
import java.util.Arrays;
import java.util.Collections;
public class TestShuffle {
public static void main(String[] args) {
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
结果是:0 1 2 3 4 5 6 7 8 9.
The result is: 0 1 2 3 4 5 6 7 8 9.
我期待一个随机改组的序列。
I was expecting a randomly shuffled sequence.
推荐答案
Arrays.asList()
不能像你期望的那样应用于基本类型的数组。当应用于 int []
时, Arrays.asList()
生成一个 int的列表[ ]
s而不是整数列表
s。因此,您随机播放新创建的 int []
列表。
Arrays.asList()
can't be applied to arrays of primitive type as you expect. When applied to int[]
, Arrays.asList()
produces a list of int[]
s instead of list of Integer
s. Therefore you shuffle a newly created list of int[]
.
这是Java中可变参数和泛型的微妙行为。 Arrays.asList()
声明为
This is a subtle behaviour of variadic arguments and generics in Java. Arrays.asList()
is declared as
public static <T> List<T> asList(T... a)
因此,它可能需要某些类型的几个参数 T
并生成一个包含这些参数的列表,或者它可以采用类型 T []
的一个参数并返回由此支持的列表数组(即可变参数的工作方式)。
So, it can take several arguments of some type T
and produce a list containing these arguments, or it can take one argument of type T[]
and return a list backed by this array (that's how variadic arguments work).
但是,后者选项仅在 T
是引用类型时才有效(即不是原始类型,如 int
),因为只有引用类型可以用作泛型中的类型参数(并且 T
是一个类型参数)。
However, the latter option works only when T
is a reference type (i.e. not a primitive type such as int
), because only reference types may be used as type parameters in generics (and T
is a type parameter).
所以,如果你传递 int []
,你会得到 T
= int []
,您的代码无法按预期工作。但是如果传递引用类型数组(例如, Integer []
),则得到 T
= 整数
并且一切正常:
So, if you pass int[]
, you get T
= int[]
, and you code doesn't work as expected. But if you pass array of reference type (for example, Integer[]
), you get T
= Integer
and everything works:
Integer[] arr = new Integer[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
这篇关于为什么Collections.shuffle()为我的数组失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!