4

我想了解如何使用两个字符串生成唯一标识符。我的要求是为特定文档生成唯一标识符。对于 id 生成,必须使用文档“名称”和“版本”。并且应该有一种方法可以从特定文档的唯一标识符中获取“名称”和“版本”。有没有办法在java中使用UUID来做到这一点?或者这样做的最佳方法是什么。我们可以为此目的使用散列或编码吗?如果可以,怎么做?

4

4 回答 4

3

我不知道您为什么要使用 2 个字符串来生成唯一 ID,并且在某些情况下可能无法保持唯一性。java.util.UUID为您的案例提供有用的方法。看看这个用法:

import java.util.UUID;

...

UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();

如果您对通过这种方式生成的 ID 不满意,您可以将名称和版本等附加参数附加/前置到生成的 ID 中。

于 2013-06-10T18:39:38.397 回答
0

您可以使用静态工厂方法randomUUID()来获取UUID对象:

UUID id = UUID.randomUUID();    

要将 id 与版本结合起来,请提供一个您知道不会出现在任何字符串中的分隔符,例如/_。然后您可以split在该分隔符上或使用正则表达式来提取您想要的内容:

String entry = id + "_" + version;
String[] divided = entry.split(delimiter);

//or using regex

String entry= "idName_version"; //delimiter is "_"
String pattern = "(.*)_(.*)";

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(example);

if (m.find())
{
    System.out.println(m.group(1)); //prints idName
    System.out.println(m.group(2)); //prints version
}
于 2013-06-10T18:44:09.573 回答
0

最好的方法是将字符串与通常不会出现在这些字符串中的分隔符连接起来

例如

String name = ....
String version = .....
String key = name + "/" + version;

您可以通过以下方式获取原始名称和版本split("/")

于 2013-06-10T18:39:43.580 回答
0

如果您不想创建 UUID,只需将其保留为纯字符串

String.format("%s_%s_%s_%s", str1.length(), str2.length(), str1, str2);

用以下测试

Pair.of("a", ""),      // 'a'   and ''    into '1_0_a_'
Pair.of("", "a"),      // ''    and 'a'   into '0_1__a'
Pair.of("a", "a"),     // 'a'   and 'a'   into '1_1_a_a'
Pair.of("aa", "a"),    // 'aa'  and 'a'   into '2_1_aa_a'
Pair.of("a", "aa"),    // 'a'   and 'aa'  into '1_2_a_aa'
Pair.of("_", ""),      // '_'   and ''    into '1_0___'
Pair.of("", "_"),      // ''    and '_'   into '0_1___'
Pair.of("__", "_"),    // '__'  and '_'   into '2_1_____'
Pair.of("_", "__"),    // '_'   and '__'  into '1_2_____'
Pair.of("__", "__"),   // '__'  and '__'  into '2_2______'
Pair.of("/t/", "/t/"), // '/t/' and '/t/' into '3_3_/t/_/t/'
Pair.of("", "")        // ''    and ''    into '0_0__'

这是有效的,因为开头创建了一种使用数字不能存在的分隔符来解析以下内容的方法,如果使用像“0”这样的分隔符,它将失败

其他示例依赖于两个字符串中都不存在的分隔符

str1+"."+str2
// both "..","." and ".",".." result in "...."

编辑

支持组合 'n' 字符串

private static String getUniqueString(String...srcs) {
  StringBuilder uniqueCombo = new StringBuilder();
  for (String src : srcs) {
    uniqueCombo.append(src.length());
    uniqueCombo.append('_');
  }
  // adding this second _ between numbers and strings allows unique strings across sizes
  uniqueCombo.append('_');
  for (String src : srcs) {
    uniqueCombo.append(src);
    uniqueCombo.append('_');
  }
  return uniqueCombo.toString();
}
于 2016-02-23T00:05:37.780 回答