Skip to content

Instantly share code, notes, and snippets.

@diaolizhi
Last active October 22, 2018 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diaolizhi/9a74fbe53a18a39aabf217af2758013f to your computer and use it in GitHub Desktop.
Save diaolizhi/9a74fbe53a18a39aabf217af2758013f to your computer and use it in GitHub Desktop.
Java 数组随机打乱顺序
public static void shuffle(Object[] a) {
//判断数组 a 是否可以转为整型数组
validateNotNull(a);
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + uniform(n-i); // between i and n-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
public static int uniform(int n) {
if (n <= 0) throw new IllegalArgumentException("argument must be positive: " + n);
return random.nextInt(n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment