Search code examples
javahexuuid

Custom hex UUID template generator in Java


I have the following code (written by AI) that generates templates for uuids (It is template only, the prefix of 8 digits and postfix of 12 will be appended computed on different logic):

import java.util.concurrent.atomic.AtomicInteger;

public class CustomUUIDGeneratorTemplate {
    private static final AtomicInteger COUNTER = new AtomicInteger(-1);

    public static String generateUUIDTemplate() {

        int count1 = COUNTER.incrementAndGet();

        String uuid = String.format("%04x-7%03x-%04x",
                count1 & 0xFFFFFFFFL,
                count1 & 0xFFFFFFFFL,
                count1 & 0xFFFFFFFFL
        );

        return uuid;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(generateUUIDTemplate());
        }
    }
}

It produces the following output:

0000-7000-0000
0001-7001-0001
0002-7002-0002

But I'm trying to achieve a different output:

0000-7000-0001
0000-7000-0002
0000-7000-0003

When the last digits are near the end, the digits on the left should increment and look like this:

0000-7fff-ffff
0001-7000-ffff

How to achieve this? Any help would be appreciated.


Solution

  • First of all, why do you want to create a custom template? The format for a UUID is very tightly defined (see here).

    But if you insist, I'd use java.util.UUID and chop off the beginning and end because you are looking for a valid subset of a UUID.

    public static String dumbUUID() {
        return UUID.randomUUID().toString().substring(4, 18);
    }