[英]Elegant way to assign object id in Java
I have a class for objects ... lat's say apples. 我有一个对象类...拉特说苹果。
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 谢谢
have a static int nextId
in your Apple class and increment it in your constructor. 在Apple类中有一个
static int nextId
并在构造函数中递增它。
It would probably be prudent to ensure that your incrementing code is atomic, so you can do something like this (using AtomicInteger). 确保增量代码是原子代码可能是谨慎的,所以你可以做这样的事情(使用AtomicInteger)。 This will guarantee that if two objects are created at exactly the same time, they do not share the same Id.
这将保证如果两个对象完全同时创建,则它们不共享相同的Id。
public class Apple {
static AtomicInteger nextId = new AtomicInteger();
private int id;
public Apple() {
id = nextId.incrementAndGet();
}
}
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). 相关: Jeff Atwood关于GUID (UUID) 的文章 。 It is database-related, though, but it's not clear from your question whether you want your objects to be persisted or not.
但是,它与数据库相关,但是从您的问题中不清楚您是否希望保留对象。
There is another way to get unique ID's. 还有另一种获取唯一ID的方法。 Instead of using an int or other data type, just make a class:
不要使用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! 线程安全无需同步!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.