zoukankan      html  css  js  c++  java
  • 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;
    	}
    }
    

      

  • 相关阅读:
    9.11 eventbus
    9.10,,,实现new instanceof apply call 高阶函数,偏函数,柯里化
    9.9 promise实现 写完了传到gitee上面了,这里这个不完整
    9.5cors配置代码
    9.5 jsonp 实现
    9.5 http tcp https总结
    9.3 es6 class一部分 and es5 class 发布订阅
    8.30 cookie session token jwt
    8.30vue响应式原理
    warning: LF will be replaced by CRLF in renard-wx/project.config.json. The file will have its original line endings in your working directory
  • 原文地址:https://www.cnblogs.com/SasaL/p/9992534.html
Copyright © 2011-2022 走看看