Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of an empty ("nil") UUID in Java

Tags:

java

uuid

null

In Java, how does one generate an instance of an empty/"nil" java.util.UUID object where all 128 bits are zero?

00000000-0000-0000-0000-000000000000

Nil UUIDs are described in:

  • Wikipedia
  • Section 4.1.7 of RFC 4122.
like image 993
Basil Bourque Avatar asked Jul 18 '15 22:07

Basil Bourque


1 Answers

Constructor

Use the constructor taking a pair of long integers, both zero.

java.util.UUID uuid = new UUID( 0 , 0 );  // Or ( 0L , 0L )

Hex String

You can create a nil UUID from a hex string of zeros in the canonical format.

java.util.UUID uuid = UUID.fromString( "00000000-0000-0000-0000-000000000000" );

Enum

You could make this handy within your Java app by defining an enum of this and any other special values that have specific meaning within your business logic.

package com.example;

import java.util.UUID;

/**
 * @author Basil Bourque. Free forever to use at your own risk.
 */
public enum UuidSpecific  {

    NIL( "00000000-0000-0000-0000-000000000000" ),
    TOLERABLE_UNIQUE_CONSTRAINT_VIOLATION( "e8e6528b-e43c-468b-b661-e24f1b64bee6" );

    // Members
    private UUID uuid;

    // Constructor
    UuidSpecific ( String uuidHexArg ) {
        this.uuid = java.util.UUID.fromString( uuidHexArg );
    }

    // Getters
    UUID getUuid ( ) {
        return this.uuid;
    }

}

Example usage:

System.out.println("UuidSpecific.NIL : " + UuidSpecific.NIL.getUuid() );
like image 185
Basil Bourque Avatar answered Sep 28 '22 06:09

Basil Bourque