How to Generate Unique ID in Java (Integer)?

后端 未结 9 1481
生来不讨喜
生来不讨喜 2020-12-06 04:11

How to generate unique ID that is integer in java that not guess next number?

相关标签:
9条回答
  • 2020-12-06 04:52
    int uniqueId = 0;
    
    int getUniqueId()
    {
        return uniqueId++;
    }
    

    Add synchronized if you want it to be thread safe.

    0 讨论(0)
  • 2020-12-06 04:53

    Just generate ID and check whether it is already present or not in your list of generated IDs.

    0 讨论(0)
  • 2020-12-06 04:56
     import java.util.UUID;
    
     public class IdGenerator {
        public static int generateUniqueId() {      
            UUID idOne = UUID.randomUUID();
            String str=""+idOne;        
            int uid=str.hashCode();
            String filterStr=""+uid;
            str=filterStr.replaceAll("-", "");
            return Integer.parseInt(str);
        }
    
        // XXX: replace with java.util.UUID
    
        public static void main(String[] args) {
            for (int i = 0; i < 5; i++) {
                System.out.println(generateUniqueId());
                //generateUniqueId();
            }
        }
    
    }
    

    Hope this helps you.

    0 讨论(0)
  • 2020-12-06 04:58

    How unique does it need to be?

    If it's only unique within a process, then you can use an AtomicInteger and call incrementAndGet() each time you need a new value.

    0 讨论(0)
  • 2020-12-06 05:01

    Do you need it to be;

    • unique between two JVMs running at the same time.
    • unique even if the JVM is restarted.
    • thread-safe.
    • support null? if not, use int or long.
    0 讨论(0)
  • 2020-12-06 05:02

    Unique at any time:

    int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
    
    0 讨论(0)
提交回复
热议问题