Generating 8-character only UUIDs

后端 未结 8 1352
[愿得一人]
[愿得一人] 2020-11-27 03:22

UUID libraries generate 32-character UUIDs.

I want to generate 8-character only UUIDs, is it possible?

相关标签:
8条回答
  • 2020-11-27 04:06

    I do not think that it is possible but you have a good workaround.

    1. cut the end of your UUID using substring()
    2. use code new Random(System.currentTimeMillis()).nextInt(99999999); this will generate random ID up to 8 characters long.
    3. generate alphanumeric id:

      char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
      Random r = new Random(System.currentTimeMillis());
      char[] id = new char[8];
      for (int i = 0;  i < 8;  i++) {
          id[i] = chars[r.nextInt(chars.length)];
      }
      return new String(id);
      
    0 讨论(0)
  • 2020-11-27 04:17

    It is not possible since a UUID is a 16-byte number per definition. But of course, you can generate 8-character long unique strings (see the other answers).

    Also be careful with generating longer UUIDs and substring-ing them, since some parts of the ID may contain fixed bytes (e.g. this is the case with MAC, DCE and MD5 UUIDs).

    0 讨论(0)
提交回复
热议问题