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

Just start using java.util.UUID. My question is if I have two UUID variables, say u1 and u2, and I would like to check if they are equal, can I safely use expression u1 == u2 or have to write u1.equals(u2)? assuming both are not null.

BTW, I am using its randomUUID method to create new UUID values, but I think this should not be matter. I wonder as UUID is unique, each value could be a singleton, then it is safe to use u1 == u2.

void method1(UUID u1, UUID u2) {

   // I know it is always safe to use equal method
   if (u1.equals(u2)){ 
     // do something
   }

   // is it safe to use  ==
   if (u1 == u2) {
     // do something
   }
}


Solution 1:[1]

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.

Solution 2:[2]

Uncommonly they are no flyweight objects because of bad ood (and wont be for compatibility reasons)! So, its a mind-trap.

Only in flyweight objects who provide a static-factory-method to create instances only you can be quite sure take usage of == instead of .equals(. Unfortunately because you have a public constructor its no flyweight-pattern.

This means you indeed have to use .equals(.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Makoto
Solution 2 Grim