在 Java 中分配对象 ID 的优雅方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4009570/
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
Elegant way to assign object id in Java
提问by user318247
I have a class for objects ... lat's say apples.
我有一个对象类...... lat 说苹果。
Each apple object mush have a unique identifier (id)... how do I ensure (elegantly and efficiently) that newly created has unique id.
每个苹果对象都必须有一个唯一的标识符 (id)……我如何确保(优雅而有效地)新创建的对象具有唯一的 id。
Thanks
谢谢
回答by Codemwnci
have a static int nextId
in your Apple class and increment it in your constructor.
static int nextId
在你的 Apple 类中有一个并在你的构造函数中增加它。
It would probably be prudent to ensure that your incrementing code is atomic, so you can do something like this (using AtomicInteger). This will guarantee that if two objects are created at exactly the same time, they do not share the same Id.
确保您的递增代码是原子的可能是谨慎的,因此您可以执行类似的操作(使用 AtomicInteger)。这将保证如果两个对象完全同时创建,它们不会共享相同的 Id。
public class Apple {
static AtomicInteger nextId = new AtomicInteger();
private int id;
public Apple() {
id = nextId.incrementAndGet();
}
}
回答by Bozho
Use java.util.UUID.randomUUID()
利用 java.util.UUID.randomUUID()
It is not int
, but it is guaranteed to be unique:
它不是int
,但保证是唯一的:
A class that represents an immutable universally unique identifier (UUID).
表示不可变的通用唯一标识符 (UUID) 的类。
If your objects are somehow managed (for example by some persistence mechanism), it is often the case that the manager generates the IDs - taking the next id from the database, for example.
如果您的对象以某种方式进行管理(例如通过某种持久性机制),通常情况下管理器会生成 ID - 例如,从数据库中获取下一个 ID。
Related: Jeff Atwood's article on GUIDs(UUIDs). It is database-related, though, but it's not clear from your question whether you want your objects to be persisted or not.
相关:Jeff Atwood 关于 GUID(UUID)的文章。但是,它与数据库相关,但是从您的问题中不清楚您是否希望对象被持久化。
回答by Amir Raminfar
回答by Ishtar
There is another way to get unique ID's. Instead of using an int or other data type, just make a class:
还有另一种获取唯一 ID 的方法。不使用 int 或其他数据类型,只需创建一个类:
final class ID
{
@Override
public boolean equals(Object o)
{
return this==o;
}
}
public Apple
{
final private ID id=new ID();
}
Thread safe without synchronizing!
线程安全,无需同步!