To compare UUID, can I use == or have to use UUID.equals(UUID)?

It depends: which type of equality do you want?

UUID a = new UUID(12345678, 87654321);
UUID b = new UUID(12345678, 87654321);
UUID c = new UUID(11111111, 22222222);

System.out.println(a == a); // returns true
System.out.println(a.equals(a)); // returns true

System.out.println(a == b); // returns false
System.out.println(a.equals(b)); // returns true

System.out.println(a == c); // returns false
System.out.println(a.equals(c)); // returns false

a == b is true only if a and b are the same object. If they are two identical objects, it will still be false.

a.equals(b) is true if a and b are the same UUID value – if their two parts are the same.

It’s a rhetorical question, by the way. Almost always you want .equals. There isn’t much use for == with UUIDs.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)