- 案例一:自动选择器:
- 案例一代码实现:
import java.util.*;
public class text {
public static void main(String[] args) {
//第一种实现方式
List<String> list=new ArrayList<>();
Collections.addAll(list,"张三","李四","王五","赵六","前妻");
Random random=new Random();
int i = random.nextInt(list.size());
String s=list.get(i);
System.out.println(s);
//第二种实现方式
Collections.shuffle(list);
System.out.println(list.get(0));
}
} - 案例2:
- 案例二代码实现:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class text2 {
public static void main(String[] args) {
//创建集合
ArrayList<Integer> arrayList=new ArrayList<>();
//添加数据
Collections.addAll(arrayList,1,1,1,1,1,1,1);
Collections.addAll(arrayList,0,0,0);
//打乱集合中的数据
Collections.shuffle(arrayList);
//从集合中随机抽取0或1
Random random=new Random();
int index = random.nextInt(arrayList.size());
int number=arrayList.get(index);
//创建两个集合分别储存男生和女生的名字
ArrayList<String> boyList=new ArrayList<>();
ArrayList<String> girlList=new ArrayList<>();
//添加数据
Collections.addAll(boyList,"刘宇坚","李进","许德俊","周文杰","张宇坤");
Collections.addAll(boyList,"邱静","张芊","熊伟仪");
//根据0和1从集合中取值
if (number==1){
int bindex=random.nextInt(boyList.size());
System.out.println(boyList.get(bindex));
}else {
int gindex=random.nextInt(boyList.size());
System.out.println(boyList.get(gindex));
}
}
} - 案例3:
- 案例3代码实现;