Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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
   }
}
like image 852
Newyacht Zhang Avatar asked May 11 '14 04:05

Newyacht Zhang


People also ask

Can I compare UUID?

The compareTo() method of UUID class in Java is used to compare one UUID value with another specified UUID. It returns -1 if this UUID is less than the value, 0 if this UUID is equal to the value, and 1 if this UUID is greater than the value.

How do you compare two UUIDs in Python?

As Giacomo Alzetta says, UUIDs can be compared as any other object, using == . The UUID constructor normalises the strings, so that it does not matter if the UUID is in a non-standard form. You can convert UUIDs to strings using str(x) , or strings into UUID objects using uuid.

How do you represent UUID in Java?

Java UUID Representation The representation of the UUID uses hex digits. Java UUID is made up of hex digit along with four hyphens (-). It is 36 characters long unique number, including four hyphens. A UUID may be nil, in which all bits are set to zero.


2 Answers

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.

like image 131
user253751 Avatar answered Oct 04 '22 19:10

user253751


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.

like image 36
Makoto Avatar answered Oct 04 '22 20:10

Makoto