2016-03-05 79 views
0

如何可以洗牌下面陣列如何洗牌字符串數組

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"]; 

後意味着,例如,如果從firstName變化"a"指數從0至4 ,相應指數爲"p","10","1"將從0改爲4 ..

+1

@Sabik JavaScript不是Java。 – MikeCAT

+0

你是從某個東西開始還是希望有人會將你的代碼轉儲? –

+0

完成此操作的最佳方法之一是使用這4個字符串字段創建自定義對象。然後你可以有一個構造函數,比如'MyObject(String fN,String lN,String sal,String pN)'並用它來設置初始值。然後創建一個'MyObject'數組 –

回答

0

剛創建它具有價值

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 .... 
} 
+0

如果我的數組的長度是X,那麼該怎麼辦? – rva

+0

以上所有您使用的示例都使用相同的排序順序。所以我認爲你有一個設定的順序和長度。洗牌需要隨機? –

+0

多數民衆贊成多數民衆贊成在我需要的數組未知的一些X長度 – rva

2

如果任務不落實的鼻塞算法,可以數組(或列表)使用標準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()]); 
+0

謝謝你的答案,但我已經得到解決方案 – rva