Search code examples
java

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


Just started 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 the 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 matter. Since UUIDs are unique, each value could be a singleton, so I wonder if 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

  • It depends:

    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 if a and b are the same object, not if they are two objects with the same parts.

    a.equals(b) is true if the parts of a and b are the same.