我需要随机打乱以下字符串数组:
String[] cardsSet1 = {"Name1", "Name2", "Name3"};
有什么办法吗?
答案1
您可以使用内置的(如发布这里):
Collections.shuffle(Arrays.asList(cardsSet1));
或者重新发明轮子:
如果要复制到新数组(保持原始数组完整):
public static String[] Randomize(String[] arr) {
String[] randomizedArray = new String[arr.length];
System.arraycopy(arr, 0, randomizedArray, 0, arr.length);
Random rgen = new Random();
for (int i = 0; i < randomizedArray.length; i++) {
int randPos = rgen.nextInt(randomizedArray.length);
String tmp = randomizedArray[i];
randomizedArray[i] = randomizedArray[randPos];
randomizedArray[randPos] = tmp;
}
return randomizedArray;
}
或者如果您想就地执行此操作(与上面的非常相似):
public static void RandomizeInPlace(String[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int randPos = rgen.nextInt(arr.length);
String tmp = arr[i];
arr[i] = arr[randPos];
arr[randPos] = tmp;
}
}
... 我应该先问“你尝试了什么”?