我有一个数组
String[] arr={"a","b","c","d","e","f","a","d","m","e"};
我想从这个数组中随机获得 4 个不同的数字。我该怎么做?
List<String> shuffled = Collections.shuffle(Arrays.asList(arr));
List<String> fourRandoms = shuffled.subList(0, 4);
或者,如果您想保持数组不变:
List<String> shuffled = Collections.shuffle(new ArrayList<String>(Arrays.asList(arr)));
List<String> fourRandoms = shuffled.subList(0, 4);
编辑:要从数组中删除重复项,请使用 Set:
Set<String> uniqueValues = new HashSet<String>(Arrays.asList(arr));
List<String> shuffled = Collections.shuffle(new ArrayList<String>(uniqueValues));
List<String> fourRandoms = shuffled.subList(0, 4);
学习标准的 Java 集合,完全避免使用数组。如果不允许重复,则应从头开始使用 Set。