生成随机数
import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; /** * 获取随机数 * * @author * */ public class RandomUtils { private static final Random random = new Random(); private static final DecimalFormat fourdf = new DecimalFormat("0000"); private static final DecimalFormat sixdf = new DecimalFormat("000000"); public static String getFourBitRandom() { return fourdf.format(random.nextInt(10000)); } public static String getSixBitRandom() { return sixdf.format(random.nextInt(1000000)); } /** * 给定数组,抽取n个数据 * @param list * @param n * @return */ public static ArrayList getRandom(List list, int n) { Random random = new Random(); HashMap<Object, Object> hashMap = new HashMap<Object, Object>(); // 生成随机数字并存入HashMap for (int i = 0; i < list.size(); i++) { int number = random.nextInt(100) + 1; hashMap.put(number, i); } // 从HashMap导入数组 Object[] robjs = hashMap.values().toArray(); ArrayList r = new ArrayList(); // 遍历数组并打印数据 for (int i = 0; i < n; i++) { r.add(list.get((int) robjs[i])); System.out.print(list.get((int) robjs[i]) + "\t"); } System.out.print("\n"); return r; } public static String getRandom(){ //Random类 Random random=new Random();//随机生成器 //范围在26个大小写字母,与10个数字之间 char[] chars = new char[]{ 'a','b','c','d','e' ,'f','g','h','i','j','k' ,'m','n','p','q','r','s' ,'t','u','v','w','x','y' ,'z', 'A','B','C','D','E' ,'F','G','H','J','K' ,'M','N','P','Q','R','S' ,'T','U','V','W','X','Y' ,'Z', '2','3','4','5','6','7','8','9'}; String code =""; //遍历4次得到4个随机整数,再把随机整数作为数组下标得到对象的字符 for(int i=0;i<4;i++){ int index=random.nextInt(chars.length);//每次遍历生成数组长度范围内的随机整数 //System.out.println(index); //生成数组中的随机整数作为下标得到对应的字符值,字符串加字符结果为字符串 code+=chars[index]; } return code; } }