我有一个 arraylist 包含一些按顺序排列的值(正确的位置),现在我想滑动/设置/手动洗牌将值更改为 arraylist 的无序。下图可以给出我的想法。将 Array-II 更改为 Array-I。要随机播放我们可以使用 collection.shuffle(),但这里我有一个文本文件,在该文本文件中我将原始位置以及数组中数据的当前位置写入文本文件。例如成像,我们有一个文本文件名称 MyFile.txt,我在里面写了这样的数据,例如“original_position~Current_position” 0~0 1~2 2~4 3~3 4~1 因此,根据上述数据,我将对数组进行洗牌/设置。
最佳答案
使用 Collections.shuffle(YOUR_ARRAY_LIST);
来完成。
List<String> ranList = new ArrayList<String>();
// populate the list
ranList.add("A");
ranList.add("B");
ranList.add("C");
System.out.println("Initial collection: " + ranList);
// shuffle the list
Collections.shuffle(ranList);
System.out.println("Final collection after shuffle: " + ranList);
人工排序的方法是这样的:
从文件读取数据并将其添加到 Map
private static Map<String, String> readFile(String fileNameWithPath) throws Exception {
Map<String, String> map = new LinkedHashMap<String, String>();
File file = new File(fileNameWithPath);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String sCurrentLine;
String[] splitPosition;
while ((sCurrentLine = bufferedReader.readLine()) != null) {
splitPosition = sCurrentLine.split("~");
map.put(splitPosition[0], splitPosition[1]);
}
return map;
}
你的主要方法是这样的:
try {
List<String> list = new ArrayList<String>();
List<String> customeRandomList = new LinkedList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
Map<String, String> map = Test.readFile("D://RandomList.txt");
for (Map.Entry<String, String> entry : map.entrySet()) {
customeRandomList.add(list.get(Integer.parseInt(entry.getValue())));
}
for (String result : customeRandomList) {
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
}
关于java - 如何手动打乱数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22809348/