-
package org.lazyman.util import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.math.RandomUtils; /** * @author yihuan * @version RandomNumberUtil.java 2010-1-14 上午11:39:20 */ public class RandomNumberUtil { private static final int[] prefix = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; /** * 随机产生最大为18位的long型数据(long型数据的最大值是9223372036854775807,共有19位) * * @param digit * 用户指定随机数据的位数 */ public static long randomLong(int digit) { if (digit >= 19 || digit <= 0) throw new IllegalArgumentException("digit should between 1 and 18(1<=digit<=18)"); String s = RandomStringUtils.randomNumeric(digit - 1); return Long.parseLong(getPrefix() + s); } /** * 随机产生在指定位数之间的long型数据,位数包括两边的值,minDigit<=maxDigit * * @param minDigit * 用户指定随机数据的最小位数 minDigit>=1 * @param maxDigit * 用户指定随机数据的最大位数 maxDigit<=18 */ public static long randomLong(int minDigit, int maxDigit) { if (minDigit > maxDigit) { throw new IllegalArgumentException("minDigit > maxDigit"); } if (minDigit <= 0 || maxDigit >= 19) { throw new IllegalArgumentException("minDigit <=0 || maxDigit>=19"); } return randomLong(minDigit + getDigit(maxDigit - minDigit)); } private static int getDigit(int max) { return RandomUtils.nextInt(max + 1); } /** * 保证第一位不是零 * * @return */ private static String getPrefix() { return prefix[RandomUtils.nextInt(9)] + ""; } }
巧用RandomStringUtils生成随机数
本文介绍了一个实用的Java工具类——随机长整数生成器。该工具类能够生成指定长度或范围内的随机long型数字,适用于需要大量随机数据进行测试或初始化的场景。文章详细解释了两个主要方法:randomLong(int digit)用于生成固定长度的随机long值;randomLong(int minDigit, int maxDigit)用于生成长度介于minDigit和maxDigit之间的随机long值。

被折叠的 条评论
为什么被折叠?



