生成不重复随机码

import java.util.*;

/**
 * 随机码+时间戳+随机码的生成 (转换为long类型)
 * @author LD
 */
public   class  RandomNumberUtils  {
    public static final long MIN_VALUE = 0x8000000000000000L;

    public static final long MAX_VALUE = 0x7fffffffffffffffL;

    static final char[] digits = { '0', '1', '2', '3', '4',
            '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E',
            'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '-', '_' };

    private static String toUnsignedString(long i, int shift) {
        char[] buf = new char[64];
        int charPos = 64;
        int radix = 1 << shift;
        long mask = radix - 1;
        do {
            buf[--charPos] = digits[(int) (i & mask)];
            i >>>= shift;
        } while (i != 0);
        return new String(buf, charPos, (64 - charPos));
    }


    // j为2的次方,如转成16进制就是4,32进制就是5...
    public static String getRand(long i,int j){
        return toUnsignedString(i, j);
    }

    // 随机码+时间戳+随机码的生成
    public static Long getRand(){
        String str1,str2,str3;
        str1=getRandStr(2);
        str3=getRandStr(3);
        str2=(new Date()).getTime()+"";
        //System.out.println(str1+str2+str3);
        return Long.parseLong(str1+str2+str3);
    }

    // 主键生成
    public static String getKey(){
        return getRand(getRand(),6);
    }

    //    生成指定长度的随机串
    public static String getRandStr(Integer length){
        String str="";
        while(str.length()!=length){
            str=(Math.random()+"").substring(2,2+length);
        }
        return str;
    }

    /**
     * 获取随机码列表
     * @param number
     * @return
     */
    public static Set<String> getRandomNumberList (int number){
        Set<String> set = new HashSet<>();
        do {
            set.add(RandomNumberUtils.getKey());
        } while (set.size() != number);
        return set;
    }
    public static void main(String[] args){
        for(int i=0;i<10;i++){
            System.out.println("第"+i+"个:"+RandomNumberUtils.getKey());
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值