UUID.java Source code

Java tutorial

Introduction

Here is the source code for UUID.java

Source

//Revised from act.soap.util;

import java.util.*;
import java.security.SecureRandom;

public class UUID {
    private int d1;
    private short d2;
    private short d3;
    private byte[] d4;
    public static final UUID nil = new UUID(0, (short) 0, (short) 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
    static Random random = new Random();

    public static UUID generate() {
        int d1 = random.nextInt() % 65536;
        d1 += random.nextInt() % 65535 * 65535;
        int d2 = random.nextInt();
        int d3 = random.nextInt();
        byte[] d4 = new byte[8];
        for (int i = 0; i < 4; i++) {
            int t = random.nextInt();
            d4[i * 2] = (byte) (t % 256);
            d4[i * 2 + 1] = (byte) (t / 256 % 256);
        }
        return new UUID(d1, (short) (d2 % 65536), (short) (d3 % 65536), d4);
    }

    public UUID() {
        d1 = 0;
        d2 = 0;
        d3 = 0;
        d4 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
    }

    public UUID(int d1, short d2, short d3, byte[] d4) {
        this.d1 = d1;
        this.d2 = d2;
        this.d3 = d3;
        this.d4 = new byte[8];
        for (int i = 0; i < 8; i++)
            this.d4[i] = d4[i];
    }

    public String toString() {
        String temp1, temp2, temp3, temp4, temp;
        temp1 = Integer.toHexString(d1);
        while (temp1.length() < 8)
            temp1 = new String("0") + temp1;
        if (d2 < 0)
            temp2 = Integer.toHexString(d2 + 65536);
        else
            temp2 = Integer.toHexString(d2);
        while (temp2.length() < 4)
            temp2 = new String("0") + temp2;
        if (d3 < 0)
            temp3 = Integer.toHexString(d3 + 65536);
        else
            temp3 = Integer.toHexString(d3);
        while (temp3.length() < 4)
            temp3 = new String("0") + temp3;
        temp = temp1 + "-" + temp2 + "-" + temp3 + "-";
        for (int i = 0; i < d4.length; i++) {
            if (d4[i] < 0)
                temp4 = Integer.toHexString(d4[i] + 256);
            else
                temp4 = Integer.toHexString(d4[i]);
            while (temp4.length() < 2)
                temp4 = new String("0") + temp4;
            temp += temp4;
        }
        return temp;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(UUID.generate().toString());
        }
    }
}