To compare UUID, can I use == or have to use UUID.equals(UUID)?
Solution 1:
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.
Solution 2:
Well...no.
==
against an object checks for reference equality. That is, it checks to see if these two objects are literally the same spot in memory.
.equals()
will check for actual object equivalence. And, the Javadoc for UUID
goes into great detail to explain when two UUID
instances are equivalent.