如何在 Java(整数)中生成唯一 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2178992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Generate Unique ID in Java (Integer)?
提问by Sajad Bahmani
How to generate unique ID that is integer in java that not guess next number?
java - 如何在java中生成不猜测下一个数字的整数的唯一ID?
采纳答案by Simon Nickerson
How unique does it need to be?
它需要有多独特?
If it's only unique within a process, then you can use an AtomicInteger
and call incrementAndGet()
each time you need a new value.
如果它仅在进程中唯一,那么您可以在每次需要新值时使用AtomicInteger
and 调用incrementAndGet()
。
回答by Mykola Golubyev
Just generate ID and check whether it is already present or not in your list of generated IDs.
只需生成 ID 并检查它是否已经存在于您生成的 ID 列表中。
回答by Mark Byers
int uniqueId = 0;
int getUniqueId()
{
return uniqueId++;
}
Add synchronized
if you want it to be thread safe.
添加synchronized
,如果你希望它是线程安全的。
回答by Jim Barrows
回答by Bill K
It's easy if you are somewhat constrained.
如果您有些受限,这很容易。
If you have one thread, you just use uniqueID++; Be sure to store the current uniqueID when you exit.
如果你有一个线程,你只需使用 uniqueID++ ;退出时一定要存储当前的uniqueID。
If you have multiple threads, a common synchronized generateUniqueID method works (Implemented the same as above).
如果您有多个线程,则通用的同步 generateUniqueID 方法有效(实现方式与上述相同)。
The problem is when you have many CPUs--either in a cluster or some distributed setup like a peer-to-peer game.
问题是当你有很多 CPU 时——无论是在集群中还是在一些分布式设置中,比如点对点游戏。
In that case, you can generally combine two parts to form a single number. For instance, each process that generates a unique ID can have it's own 2-byte ID number assigned and then combine it with a uniqueID++. Something like:
在这种情况下,您通常可以将两个部分组合成一个数字。例如,每个生成唯一 ID 的进程都可以分配自己的 2 字节 ID 号,然后将其与 uniqueID++ 组合。就像是:
return (myID << 16) & uniqueID++
It can be tricky distributing the "myID" portion, but there are some ways. You can just grab one out of a centralized database, request a unique ID from a centralized server, ...
分发“myID”部分可能很棘手,但有一些方法。您可以从集中式数据库中获取一个,从集中式服务器请求唯一 ID,...
If you had a Long instead of an Int, one of the common tricks is to take the device id (UUID) of ETH0, that's guaranteed to be unique to a server--then just add on a serial number.
如果你有一个 Long 而不是 Int,一个常见的技巧是获取 ETH0 的设备 ID (UUID),这保证对服务器来说是唯一的——然后只需添加一个序列号。
回答by Pete Kirkham
If you really meant integer rather than int:
如果你的意思是整数而不是整数:
Integer id = new Integer(42); // will not == any other Integer
If you want something visible outside a JVM to other processes or to the user, persistent, or a host of other considerations, then there are other approaches, but without context you are probably better off using using the built-in uniqueness of object identity within your system.
如果您希望在 JVM 之外对其他进程或用户可见、持久性或许多其他考虑因素,那么还有其他方法,但如果没有上下文,您可能最好使用内部对象标识的内置唯一性你的系统。
回答by Peter Lawrey
Do you need it to be;
你需要它吗?
- unique between two JVMs running at the same time.
- unique even if the JVM is restarted.
- thread-safe.
- support null? if not, use int or long.
- 在同时运行的两个 JVM 之间是唯一的。
- 即使 JVM 重新启动也是唯一的。
- 线程安全。
- 支持空?如果没有,请使用 int 或 long。
回答by user1614168
import java.util.UUID;
public class IdGenerator {
public static int generateUniqueId() {
UUID idOne = UUID.randomUUID();
String str=""+idOne;
int uid=str.hashCode();
String filterStr=""+uid;
str=filterStr.replaceAll("-", "");
return Integer.parseInt(str);
}
// XXX: replace with java.util.UUID
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(generateUniqueId());
//generateUniqueId();
}
}
}
Hope this helps you.
希望这对你有帮助。
回答by Morten Holmgaard
Unique at any time:
任何时候都独一无二:
int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);