假如我有一个数组:
ArrayList<Integer> mArrayList = new ArrayList<Integer>();
mArrayList.add(0);
mArrayList.add(1);
mArrayList.add(2);
mArrayList.add(3);
我需要从中随机抽取2个数 ?不能重复抽取,我就会用这个方法
public void getValue(ArrayList<Integer> mArrayList){
Random mRandom = new Random();
int a = mRandom.nextInt(mArrayList.size());
int value = mArrayList.get(a);
System.out.println(value + "");
mArrayList.remove(a);
}
原理就是每抽取一次就删除已经抽取出来的值,这样获取到的值就不会重复了
完整代码:
class="java" name="code">package com.xiaoqiu.test;
import java.util.ArrayList;
import java.util.Random;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> mArrayList = new ArrayList<Integer>();
mArrayList.add(0);
mArrayList.add(1);
mArrayList.add(2);
mArrayList.add(3);
Test mTest = new Test();
mTest.getValue(mArrayList);
mTest.getValue(mArrayList);
}
public void getValue(ArrayList<Integer> mArrayList){
Random mRandom = new Random();
int a = mRandom.nextInt(mArrayList.size());
int value = mArrayList.get(a);
System.out.println(value + "");
mArrayList.remove(a);
}
}
?
测试结果:
3
2
3
0
2
3