Java UUID Create generateUUID(int numchars)

Here you can find the source of generateUUID(int numchars)

Description

Generated a random UUID with the specified number of characters.

License

Apache License

Parameter

Parameter Description
numchars The number of characters in the generated UUID.

Return

A new random UUID.

Declaration

public static String generateUUID(int numchars) 

Method Source Code

//package com.java2s;
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *

import java.util.*;

public class Main {
    /**/*  w  w w. j  av  a  2 s  .c  o  m*/
     * Generated a random UUID with the specified number of characters.
     * Characters are composed of lower-case ASCII letters and numbers only.
     * This method conforms to the restrictions for hostnames as specified in <a class="doclink" href="https://tools.ietf.org/html/rfc952">RFC 952</a>
     * Since each character has 36 possible values, the square approximation formula for
     *    the number of generated IDs that would produce a 50% chance of collision is:
     * <code>sqrt(36^N)</code>.
     * Dividing this number by 10 gives you an approximation of the number of generated IDs
     *    needed to produce a &lt;1% chance of collision.
     * For example, given 5 characters, the number of generated IDs need to produce a &lt;1% chance of
     *    collision would be:
     * <code>sqrt(36^5)/10=777</code>
     *
     * @param numchars The number of characters in the generated UUID.
     * @return A new random UUID.
     */
    public static String generateUUID(int numchars) {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(numchars);
        for (int i = 0; i < numchars; i++) {
            int c = r.nextInt(36) + 97;
            if (c > 'z')
                c -= ('z' - '0' + 1);
            sb.append((char) c);
        }
        return sb.toString();
    }

    /**
     * Calls {@link #toString()} on the specified object if it's not null.
     *
     * @param o The object to convert to a string.
     * @return The object converted to a string, or <jk>null</jk> if the object was null.
     */
    public static String toString(Object o) {
        return (o == null ? null : o.toString());
    }
}

Related

  1. generateUUID()
  2. generateUUID()
  3. generateUUID()
  4. generateUUID()
  5. generateUuid(boolean dash)
  6. generateUUID(Object o)
  7. generateUUID(String prefix)
  8. generateUuid(String seed)
  9. generateUUIDFileName(String fileName)