从数组中随机取出各个元素并不重复

从数组中随机取出各个元素并不重复 

1.定义一个Integer的List,且长度和要排序的数组长度相同;

2.从List随机取出一个随机数,该数相当是数组的指针;

3.移除后再从剩下的List元素里面取另一个元素,如此类推

public static void main(String[] args) {
  String[] strArray = {"a","b","c","d","e","f","g","h","i","j"};

     //定义一个Integer的List,且长度和要排序的数组长度相同;
  String[] resultStr = new String[strArray.length];
  List<Integer> intList = new ArrayList<Integer>();
  //给intList初始化
  for (int i = 0; i < strArray.length; i++) {
   intList.add(i, i);
  }
  int i = 0;
  //选出随机数
  while(intList.size()>0){
   Random random = new Random();
   int ranIdex = random.nextInt(intList.size());
   resultStr[i] = strArray[intList.get(ranIdex)];
   //移除随机数
   intList.remove(ranIdex);
   i++;
  }
  for (int j = 0; j < resultStr.length; j++) {
   System.out.println("最后的结果是========" + resultStr[j]);
   
  }
 }

猜你喜欢

转载自ronbay.iteye.com/blog/2224756