随机抽取函数Random
//随机生成一个整数
生成单个的数时的方法有两种
第一种:
public void int randomNumber(){
Random ran=new Random();
int j=ran.nextIn(10);//从十个人当中抽取一个人
return j;
}
第二种:
public int getStudentIdx() throws Exception {
Random rdm=new Random();
if (students==null)
throw new Exception("学生数组为空");
return Math.abs(rdm.nextInt())%students.length;
}
在十个人当中抽取n个人不重复
随机抽取的三种方法
1.hashset方法
public Student[] drawingStudentBySet(int n) throws Exception {
if (this.students==null || this.students.length<n)
throw new Exception("学生人数过少");
Set<Integer> stuset=new HashSet<Integer>();
do
stuset.add(new Integer(getStudentIdx()));//将获得随机数放入到stuset链表,如果数是重复的无法存入hashset当中,即stuset.set不增加
while (stuset.size()<n);
Student[] result=new Student[n] ;//因为hashset内部无序必须要用迭代器去访问,然后存入it这个容器当中
Iterator<Integer> it=stuset.iterator();//迭代器iterator遍历链表stuset
int i=0;
while (it.hasNext())
result[i++]=students[it.next()];
return result;
}
/*
迭代器(Iterator)
迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构。迭代器通常被称为“轻量级”对象,因为创建它的代价小。
Java中的Iterator功能比较简单,并且只能单向移动:
(1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。
(2) 使用next()获得序列中的下一个元素。
(3) 使用hasNext()检查序列中是否还有元素。
(4) 使用remove()将迭代器新返回的元素删除。
Iterator是Java迭代器最简单的实现,为List设计的ListIterator具有更多的功能,它可以从两个方向遍历List,也可以从List中插入和删除元素。
迭代器应用:
list l = new ArrayList();
l.add("aa");
l.add("bb");
l.add("cc");
for (Iterator iter = l.iterator(); iter.hasNext();) {
String str = (String)iter.next();
System.out.println(str);
}
/*迭代器用于while循环
Iterator iter = l.iterator();
while(iter.hasNext()){
String str = (String) iter.next();
System.out.println(str);
}
*/
方法二
public Student[] drawingStudentBySetStudent(int n) throws Exception {
if (this.students==null || this.students.length<n)
throw new Exception("学生人数过少");
Set<Student> stuset=new HashSet<Student>();
do
stuset.add(this.getStudent());
while (stuset.size()<n);
Student[] result=new Student[n] ;
return stuset.toArray(result);
}
第三种方法List表:
public Student[] drawingStudentByList(int n) throws Exception {
if (this.students==null || this.students.length<n)
throw new Exception("学生人数过少");
List<Student> stulst=new ArrayList<Student>();将学生类放入list表当中
for (Student stu:students)
stulst.add(stu);
Student[] result=new Student[n] ;
for (int i=0;i<n;i++){
int idx=this.getStudentIdx(stulst.size());
result[i]=stulst.get(idx);//从list表中随机抽取一个学生类放在result当中
stulst.remove(idx);//抽取过的学生删除,在循环抽取则没有重复的学生类
}
return result;
}
}