我有一个数组
String[] arr={"a","b","c","d","e","f","a","d","m","e"};
我想从这个数组中随机获得4个不同的数字。 我该怎么办?
答案 0 :(得分:1)
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。