随机集合中的下标,然后得到元素,并把元素移除
Random类
List<String> list2 = new ArrayList<>();
list2.add("2");
list2.add("3");
list2.add("4");
list2.add("5");
Random rand = new Random();
//随机元素
String randomElement = list2.get(rand.nextInt(list2.size()));
list2.remove(randomElement);
使用Collections.shuffle()方法
//使用Collections.shuffle()方法
List<String> list2 = new ArrayList<>();
list2.add("2");
list2.add("3");
list2.add("4");
list2.add("5");
// 随机集合中的元素
Collections.shuffle(list2);
// 默认取集合中的第一个
String randomElement = list2.get(0);
list2.remove(randomElement);
队列 queue 先进先出 符合特性
Queue<String> queue = new LinkedList<>();
queue.add("2");
queue.add("3");
queue.add("4");
queue.add("5");
List<String> list = new ArrayList<>(queue);
// 把队列中的元素随机排列
Collections.shuffle(list);
queue = new LinkedList<>(list);
while (true){
if (queue.isEmpty()){
System.out.println("queue is null");
break;
}
// 从队列中取一个元素 (FIFO先进先出)
String random = queue.poll();
System.out.println(random);
}