Why java.util.UUID is Comparable?

  • A+

UUID in java implements Comparable. Which seems a bit weird to me, since, in almost all cases UUIDs are randomly generated (or deserialized from somewhere but still they were probably originally randomly generated).

There doesn't seem to be any sense comparing them, unless you generate them manually with sequentially incremented LSB/MSB, which might make sense if you just want a very big ID number (two longs instead of one plain long), but that's the only explanation I can think of.


Some UUID versions have meaning encoded into their values:

There are four different basic types of UUIDs: time-based, DCE security, name-based, and randomly generated UUIDs.

Because of this it can make sense to compare UUID since you can derive meaning from their values. You could loosely say "This UUID was made earlier or later" than another.

Consider the versions defined on Wikipedia:

  • Version 1 (date-time and MAC address)
  • Version 2 (date-time and MAC address, DCE security version)
  • Versions 3 and 5 (namespace name-based)
  • Version 4 (random)

You can even see this in the JavaDoc:

The layout of a variant 2 (Leach-Salz) UUID is as follows: The most significant long consists of the following unsigned fields:

 0xFFFFFFFF00000000 time_low  0x00000000FFFF0000 time_mid  0x000000000000F000 version  0x0000000000000FFF time_hi 

See How is a Time-based UUID / GUID made


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: