Jak utworzyć unikalny identyfikator w Javie? [duplikat]

To pytanie ma już odpowiedź tutaj:

Szukam najlepszego sposobu na stworzenie unikalnego ID jako ciąg znaków w Javie.

Wszelkie wskazówki mile widziane, dzięki.

Powinienem wspomnieć, że używam Javy 5.

Author: Supertux, 2009-09-07

12 answers

Utwórz UUID.

String uniqueID = UUID.randomUUID().toString();
 275
Author: aperkins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-05 09:15:29

Jeśli potrzebujesz krótkich, czytelnych dla człowieka identyfikatorów i potrzebujesz ich tylko, aby były unikalne dla każdego uruchomienia JVM:

private static long idCounter = 0;

public static synchronized String createID()
{
    return String.valueOf(idCounter++);
}    

Edit: alternatywa sugerowana w komentarzach-polega to na "magii" pod maską dla bezpieczeństwa wątku, ale jest bardziej skalowalne i tak samo bezpieczne:

private static AtomicLong idCounter = new AtomicLong();

public static String createID()
{
    return String.valueOf(idCounter.getAndIncrement());
}
 41
Author: Michael Borgwardt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-07 15:38:08

java.util.UUID : metoda toString ()

 22
Author: Mitch Wheat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-07 14:50:09

Oto moja wartość dwóch centów: zaimplementowałem wcześniej klasę IdFactory, która utworzyła identyfikatory w formacie [Nazwa hosta]-[czas rozpoczęcia Aplikacji]-[czas bieżący]-[dyskryminator] . To w dużej mierze gwarantowało unikalność identyfikatorów we wszystkich instancjach JVM przy zachowaniu ich czytelności (choć dość długiej). Oto kod na wszelki wypadek:

public class IdFactoryImpl implements IdFactory {
  private final String hostName;
  private final long creationTimeMillis;
  private long lastTimeMillis;
  private long discriminator;

  public IdFactoryImpl() throws UnknownHostException {
    this.hostName = InetAddress.getLocalHost().getHostAddress();
    this.creationTimeMillis = System.currentTimeMillis();
    this.lastTimeMillis = creationTimeMillis;
  }

  public synchronized Serializable createId() {
    String id;
    long now = System.currentTimeMillis();

    if (now == lastTimeMillis) {
      ++discriminator;
    } else {
      discriminator = 0;
    }

    // creationTimeMillis used to prevent multiple instances of the JVM
    // running on the same host returning clashing IDs.
    // The only way a clash could occur is if the applications started at
    // exactly the same time.
    id = String.format("%s-%d-%d-%d", hostName, creationTimeMillis, now, discriminator);
    lastTimeMillis = now;

    return id;
  }

  public static void main(String[] args) throws UnknownHostException {
    IdFactory fact = new IdFactoryImpl();

    for (int i=0; i<1000; ++i) {
      System.err.println(fact.createId());
    }
  }
}
 16
Author: Adamski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-07 15:15:51

Dodaje to nieco więcej losowości do generowania UUID, ale zapewnia, że każdy wygenerowany identyfikator jest tej samej długości

import org.apache.commons.codec.digest.DigestUtils;
import java.util.UUID;

public String createSalt() {
    String ts = String.valueOf(System.currentTimeMillis());
    String rand = UUID.randomUUID().toString();
    return DigestUtils.sha1Hex(ts + rand);
}
 7
Author: Robert Alderson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-06 03:06:52

Java-generowanie unikalnego ID

UUID jest najszybszym i najłatwiejszym sposobem generowania unikalnego identyfikatora w Javie.
import java.util.UUID;

public class UniqueIDTest {
  public static void main(String[] args) {
    UUID uniqueKey = UUID.randomUUID();
    System.out.println (uniqueKey);
  }
}
 6
Author: pudaykiran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-19 20:15:04

IMHO aperkins pod warunkiem, że eleganckie rozwiązanie jest natywne i używa mniej kodu. Ale jeśli potrzebujesz krótszego identyfikatora, możesz użyć tego podejścia, aby zmniejszyć wygenerowaną Długość łańcucha:

// usage: GenerateShortUUID.next();
import java.util.UUID;

public class GenerateShortUUID() {

  private GenerateShortUUID() { } // singleton

  public static String next() {
     UUID u = UUID.randomUUID();
     return toIDString(u.getMostSignificantBits()) + toIDString(u.getLeastSignificantBits());
  }

  private static String toIDString(long i) {
      char[] buf = new char[32];
      int z = 64; // 1 << 6;
      int cp = 32;
      long b = z - 1;
      do {
          buf[--cp] = DIGITS66[(int)(i & b)];
          i >>>= 6;
      } while (i != 0);
      return new String(buf, cp, (32-cp));
  }

 // array de 64+2 digitos 
 private final static char[] DIGITS66 = {
    '0','1','2','3','4','5','6','7','8','9',        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
    '-','.','_','~'
  };

}
 6
Author: rharari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-04 02:23:13

Możemy utworzyć unikalny identyfikator w Javie za pomocą UUID i wywołać metodę podobną do randomUUID() na UUID.

String uniqueID = UUID.randomUUID().toString();

Spowoduje to wygenerowanie losowego uniqueID, którego typem zwracanym będzie String.

 2
Author: Prabhat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-22 15:40:43

Istnieją trzy sposoby generowania unikalnego identyfikatora w Javie.

1) klasa uuid zapewnia prosty sposób generowania unikalnych identyfikatorów.

 UUID id = UUID.randomUUID();
 System.out.println(id);

2) SecureRandom i MessageDigest

//initialization of the application
 SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");

//generate a random number
 String randomNum = new Integer(prng.nextInt()).toString();

//get its digest
 MessageDigest sha = MessageDigest.getInstance("SHA-1");
 byte[] result =  sha.digest(randomNum.getBytes());

System.out.println("Random number: " + randomNum);
System.out.println("Message digest: " + new String(result));

3) Korzystanie z Javy.rmi.serwer.UID

UID userId = new UID();
System.out.println("userId: " + userId);
 0
Author: Md Ayub Ali Sarker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-10 19:47:55

Unikalny identyfikator z informacją o liczbie

import java.util.concurrent.atomic.AtomicLong;

public class RandomIdUtils {

    private static AtomicLong atomicCounter = new AtomicLong();

    public static String createId() {

        String currentCounter = String.valueOf(atomicCounter.getAndIncrement());
        String uniqueId = UUID.randomUUID().toString();

        return uniqueId + "-" + currentCounter;
    }
}
 0
Author: simhumileco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-22 16:14:11
String name,password;

public int idGen() {

    int id = this.name.hashCode() + this.password.hashCode();
    int length = String.valueOf(id).length();
    int Max_Length = 5;
    if(String.valueOf(id).length()>Max_Length) 
    {
        id = (int) (id /Math.pow(10.0,length - Max_Length ));
    }
    return  id;
}
 0
Author: Hatim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-26 19:50:33
enter code here

Program do generowania unikalnych identyfikatorów

class Test {

    public static void main(String arg[]) {

        String s = "";
        double d;
        for (int i = 1; i <= 16; i++) {
            d = Math.random() * 10;
            s = s + ((int)d);
            if (i % 4 == 0 && i != 16) {
                s = s + "-";
            }
        }

        System.out.println(s);
    }
}

Wyjście:

7954-7605-1827-4795
1991-4912-4912-3008
 -5
Author: jonathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 11:16:11