java 随机抽取案例,不重复抽取
以学生类为例,先准备一个Student类
package cn.sasa.demo1; public class Student { private int id; private String name; public int getId() { return this.id; } public void setId(int id) { if(id<0) { this.id = 0; }else { this.id = id; } } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public void SayHi() { System.out.println(this.id + "======" + this.name); } }
测试类TestStudent:
package cn.sasa.demo1; import java.util.ArrayList; import java.util.Random; public class TestStudent { public static void main(String[] args) { //要求随机抽取三次,不重复 ArrayList<Student> stuList = addStu(); showStuList(stuList); getRanStu(stuList); showStuList(stuList); getRanStu(stuList); showStuList(stuList); getRanStu(stuList); showStuList(stuList); } public static ArrayList<Student> addStu() { ArrayList<Student> stuList = new ArrayList<Student>(); Student s1 = new Student(); s1.setId(1); s1.setName("abc"); Student s2 = new Student(); s2.setId(2); s2.setName("bcd"); Student s3 = new Student(); s3.setId(3); s3.setName("cde"); Student s4 = new Student(); s4.setId(4); s4.setName("def"); Student s5 = new Student(); s5.setId(5); s5.setName("efg"); Student s6 = new Student(); s6.setId(6); s6.setName("fgh"); stuList.add(s1); stuList.add(s2); stuList.add(s3); stuList.add(s4); stuList.add(s5); stuList.add(s6); return stuList; } public static void showStuList(ArrayList<Student> stuList) { System.out.println("===================================="); for(int i = 0; i < stuList.size(); i++) { stuList.get(i).SayHi(); } } public static Student getRanStu(ArrayList<Student> stuList) { System.out.println("===================================="); Random ran = new Random(); int i = ran.nextInt(stuList.size()); Student stu = stuList.get(i); stuList.remove(i); stu.SayHi(); return stu; } }