取一定范围的的数字,随机顺序。

  1. 运用Collections中的shuffle方法,将已经按顺序放好的list进行乱序处理。
  2. public void RangeRandom(){
List<Integer> list =new ArrayList<Integer>();
for(int i=0;i<5;i++){  
list.add(i);
}
Collections.shuffle(list);  //将顺序打乱
for(int i:list){
System.out.println("==========="+list.get(i));
}

}
        3.网上还有其他的方法:
        转载https://blog.csdn.net/Scaarf/article/details/70862369
        

从list和数组中随机抽取若干不重复元素, 
这里的重复是指索引位置重复, 
也就是不会重复取到同一索引位置上的元素。就像人一样,名字可能会相同但身份证号不可能会相同

从数组中随机抽取若干不重复元素

    /**
     * @function:从数组中随机抽取若干不重复元素
     * 
     * @param paramArray:被抽取数组
     * @param count:抽取元素的个数
     * @return:由抽取元素组成的新数组
     */
    public static String[] getRandomArray(String[] paramArray,int count){
        if(paramArray.length<count){
            return paramArray;
        }
        String[] newArray=new String[count];
        Random random= new Random();
        int temp=0;//接收产生的随机数
        List<Integer> list=new ArrayList<Integer>();
        for(int i=1;i<=count;i++){
            temp=random.nextInt(paramArray.length);//将产生的随机数作为被抽数组的索引
            if(!(list.contains(temp))){
                newArray[i-1]=paramArray[temp];
                list.add(temp); 
            }
            else{
                i--;
            }
        }
        return newArray;
    }

从list中随机抽取若干不重复元素

    /**
     * @function:从list中随机抽取若干不重复元素
     *
     * @param paramList:被抽取list
     * @param count:抽取元素的个数
     * @return:由抽取元素组成的新list
     */
    public static List getRandomList(List paramList,int count){
        if(paramList.size()<count){
            return paramList;
        }
        Random random=new Random();
        List<Integer> tempList=new ArrayList<Integer>();
        List<Object> newList=new ArrayList<Object>();
        int temp=0;
        for(int i=0;i<count;i++){
            temp=random.nextInt(paramList.size());//将产生的随机数作为被抽list的索引
            if(!tempList.contains(temp)){
                tempList.add(temp);
                newList.add(paramList.get(temp));
            }
            else{
                i--;
            }   
        }
        return newList;
    }

猜你喜欢

转载自blog.csdn.net/qq_35384887/article/details/80389073