巧用RandomStringUtils生成随机数

RandomStringUtils.random(5);//产生5位长度的随机字符串

//使用指定的字符生成5位长度的随机字符串
RandomStringUtils.random(5, new char[]{'a','b','c','d','e','f'});

//生成指定长度的字母和数字的随机组合字符串
RandomStringUtils.randomAlphanumeric(5);

//生成随机数字字符串
RandomStringUtils.randomNumeric(5);

Java提供的随机数工具,或者第三方提供的随机数工具,都不能满足我的需求:产生指定位数且大于0的整数(可以做为ID使用)。
在使用commons-lang的RandomStringUtils类时,有一个方法引起了我的注意RandomStringUtils.randomNumeric(int count),该方法返回指定数目的随机数字串,如果把返回的数字串解析成数字,不就可以产生随机数了么~~~~
按照上面的思路,做了一下封装,代码如下:

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)] + "";
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值