随机生成一个不重复的字符串或数字

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xinyuezitang/article/details/90440121

一 要求随机生成一个字符串, 要求该字符串不在原来的字符串列表当中即可,再将生成的字符串添加到列表中, 生成新的字符串列表

public class Test {

    public static void main(String[] args) {
        List<String> macTypeIdList = new ArrayList<>();
        macTypeIdList.add("500396");
        macTypeIdList.add("500903");
        macTypeIdList.add("500749");
        macTypeIdList.add("500808");
        macTypeIdList.add("500101");
        String typeId ="000";
        String supplierId = "500";
        Random random = new Random();
        while (true){
            int serialNum = random.nextInt(900) + 100;
            typeId = supplierId + serialNum;
            if (!macTypeIdList.contains(typeId)){
                System.out.println(typeId);
                System.out.println(macTypeIdList);
                break;
            }
        }
    }
}

二 要求随机一个Long类型的设备类型id, 要求该数字不在原来的List设备Id列表当中即可. 设备类型Id = 500 + 一个三位数的随机数, 新生成的设备id添加到列表当中,形成新的列表

代码:

 public static void main(String[] args) {
    List<Long> macTypeIdList = new ArrayList<>();
    macTypeIdList.add(500396L);
    macTypeIdList.add(500903L);
    macTypeIdList.add(500749L);
    macTypeIdList.add(500808L);
    macTypeIdList.add(500101L);
    long typeId = 0;
    int supplierId = 500;
    Random random = new Random();
    while (true){
        int serialNum = random.nextInt(900) + 100;
        typeId = Long.parseLong (String.valueOf(supplierId)+String.valueOf(serialNum));
        if (!macTypeIdList.contains(typeId)){
            System.out.println(typeId);
            break;
        }
    }

    macTypeIdList.add(typeId);
    System.out.println(macTypeIdList);
}

控制台输出:
在这里插入图片描述

延伸思考:

当设备类型Id列表是从数据库中获取的, 
设备类型Id 数量一直添加, 理论上会不会进入死循环, 内存溢出.???

个人觉得会, 设备类型Id不能重复,  并且最后由一个三位数的随机数拼接, 100-999是900个.
实际上也就规定了macTypeIdList的数量不能超过900个.
当数据库获取的数量没有超过900个时, 是没有问题的, 超出就会进入死循环.
如何优化?

代码如下:

public class Test {

    public static void main(String[] args) {
        List<Long> macTypeIdList = new ArrayList<>();
        macTypeIdList.add(500396L);
        macTypeIdList.add(500903L);
        macTypeIdList.add(500749L);
        macTypeIdList.add(500808L);
        macTypeIdList.add(500101L);
       // ...
        
        long typeId = 0;
        int supplierId = 500;
        Random random = new Random();

        if(macTypeIdList.size()< 900){

            while (true){
                int serialNum = random.nextInt(900) + 100;
                typeId = Long.parseLong (String.valueOf(supplierId)+String.valueOf(serialNum));
                if (!macTypeIdList.contains(typeId)){
                    System.out.println(typeId);
                    macTypeIdList.add(typeId);
                    System.out.println(macTypeIdList);
                    break;
                }
            }
        }else{
            System.out.println("macTypeId的数量已达上限");
        }

}

猜你喜欢

转载自blog.csdn.net/xinyuezitang/article/details/90440121
今日推荐