Random产生不重复数字问题?

public void testSort1() {
		Integer k;
		List<Integer> intList=new ArrayList<Integer>();
		Random random=new Random();
		for(int i=0;i<10;i++) {
			do {
				k=random.nextInt(5);
			}while(intList.contains(k));//因为这里判断条件需要
			
//把这句话去掉就会打印出重复的K值,为什么???
			intList.add(k);


			System.out.println("添加的k为:"+k);
		}

打印输出:

添加的k为:2
添加的k为:4
添加的k为:3
添加的k为:1
添加的k为:0

猜你喜欢

转载自blog.csdn.net/weixin_43592833/article/details/85255129
今日推荐