-1

Do UUID in Java for String objects will be the same if those strings are equal? If not, Is there a way/tool to generate string (with proper UUID format) that will stay the same if will be computed on equal string? I need some kind of hash for string, that keep UUID format. Is there something like this in Java?

[Edit]: You will propably ask what exacly I am trying to do. I am making a part of application that will translate object from one servis to another. One of those servises indentity object by UUID. Second one do not store it. I do not want to cach whole data of those services, so I have to generate that UUID somehow.

M314
  • 925
  • 3
  • 13
  • 37

3 Answers3

0

Do UUID in Java for String objects will be the same if those strings are equal?

No, since this prints false:

final String s = "Mémé dans les orties ";
final UUID uuid1 = UUID.nameUUIDFromBytes(s.getBytes(StandardCharsets.UTF_8));
final UUID uuid2 = UUID.nameUUIDFromBytes(s.getBytes(StandardCharsets.UTF_16LE));
System.out.println(uuid1.equals(uuid2));

You need to encode the String into a byte array and use the same encoding on both sides.


What is more, a UUID is not a hash per se; if you want hashes like sha1, sha256 etc, have a look at Guava

fge
  • 119,121
  • 33
  • 254
  • 329
0

try this

    MessageDigest md = MessageDigest.getInstance("MD5");  
    md.update("test".getBytes());
    byte[] a = md.digest();     // 16 bytes for MD5
    ByteBuffer bb = ByteBuffer.wrap(a);
    long l1 = bb.getLong();
    long l2 = bb.getLong();
    UUID uuid = new UUID(l1, l2);
    System.out.println(uuid);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Yes. You just have to use UUID.fromString() with the result of uuid.toString():

UUID id1 = UUID.randomUUID();
String s = id1.toString();
UUID id2 = UUID.fromString(s);

assertTrue(id1, id2);
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820