如何随机播放字符串数组

时间:2016-03-05 09:07:01

标签: java arrays string random shuffle

如何在阵列下面随机播放

String[] firstName =["a","b","c","d","e"];
String[] lastName =["p","q","r","s","t"];
String[] salary =["10","20","30","40",50"];
String[] phoneNo= ["1","2","3","4","5"];

在洗牌之后,我需要像

这样的结果
String[] firstName =["d","b","e","c","a"];
String[] lastName =["s","q","t","r","p"];
String[] salary =["40","20","50","30",10"];
String[] phoneNo= ["4","2","5","3","1"];

表示例如来自"a"的{​​{1}}索引从0更改为4,firstName"p""10"的相应索引将从0到4 ..

2 个答案:

答案 0 :(得分:5)

如果你的任务不是snuffle算法的实现,你可以使用标准的java.util.Collections#shuffle方法:

String[] firstName = new String[] {"a","b","c","d","e"};
List<String> strList = Arrays.asList(firstName);
Collections.shuffle(strList);
firstName = strList.toArray(new String[strList.size()]);

答案 1 :(得分:1)

只需创建一个具有值

的数组(或列表)
Integer[] arr = new Integer[firstName.length];
for (int i = 0; i < arr.length; i++) {
    arr[i] = i;
}

Collections.shuffle(Arrays.asList(arr));

然后创建一个新的字符串数组以将值移动到

string[] newFirstName = new string[arr.length]();
for(int i=0; i < arr.length; i++)
{
    newFirstName[i] = firstName[arr[i]];
    //etc ....
}