为每个对象实例生成尽可能低的ID号-java
我想按照以下规则为对象生成ID号: 每个新对象将获得一个唯一的ID号(第一个ID号为1), 然后每个新对象将获得最低的可用ID号 例如,如果我声明4个对象 对象1 ID:1 对象2 ID:2 对象3 ID:3 对象4 ID:4 然后,如果我删除对象编号3。 因此,将生成的下一个对象将获得ID:3,而不是5为每个对象实例生成尽可能低的ID号-java,java,unique-key,Java,Unique Key,我想按照以下规则为对象生成ID号: 每个新对象将获得一个唯一的ID号(第一个ID号为1), 然后每个新对象将获得最低的可用ID号 例如,如果我声明4个对象 对象1 ID:1 对象2 ID:2 对象3 ID:3 对象4 ID:4 然后,如果我删除对象编号3。 因此,将生成的下一个对象将获得ID:3,而不是5 做这个ID生成器的最好方法是什么?我想你应该用Java来做。我建议如下: 具有用于为实体提供ID的序列。它非常简单,我认为不需要详细解释——它只返回1、2、3等等 现在我们需要处理删除。连同我
做这个ID生成器的最好方法是什么?我想你应该用Java来做。我建议如下:
SortedSet
,该ID已被删除,可以分配给新的实体- 如果集合不是空的,则返回其第一个值并将其从集合中删除。它将是最低值,因为您使用的是
SortedSet
- 如果为空,只需返回序列中的下一个数字
当然,您将需要处理此操作的原子性,并且可能会遇到并发问题,但对它的详细讨论对于这个问题来说有点离题。您可以使用
ConcurrentHashMap
来设置要使用的唯一ID。使用布尔值检查它们是否被使用。然后,使用ConcurrentHashMap
将所需对象存储在其相关ID内。因此,您必须手动同步两个结构的添加/删除,以始终定义可用的最低键
请注意,拥有所有这些都是非常昂贵和难以维护的。最好使用第三方元素(可能是嵌入式数据库?)为您处理所有这些问题。注意:这是我的方法,因为我不知道列表。如果有一个列表在没有算法的情况下完成了这个问题,那就太好了。不要因为我的答案没有必要就投反对票
我想您可以有一个,只需从中添加ID,并始终使用可用的最低ID
例如:
static ArrayList<Integer> ids = new ArrayList<Integer>();
public static void assignId() {
boolean foundId = false;
for (int i = 0; i < ids.size(); i++) {
if (ids.get(i) < 0) { // if it's negative, it was removed before
// make object ID to be i+1
ids.set(i, i+1); // and add it to the list
foundId = true;
break;
}
}
if (!foundId) { // can't find ID mid list to fill in
ids.add(ids.size()+1); // so give it a brand new one
}
}
public static void removeId(int id) {
ids.set(id-1, -1); // negative value means it was removed
}
// assign five IDs (1 through 5)
assignId();
assignId();
assignId();
assignId();
assignId();
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, 3, 4, 5,
// now remove the id 3
removeId(3);
removeId(2);
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, -1, 4, 5,
assignId(); // give this new object a new id (should be 2 replacing -1)
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, -1, 4, 5,
assignId(); // give this new object a new id (should be 3 replacing -1)
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, 3, 4, 5,
assignId(); // give this new object a new id (should a brand new ID)
// print ids for testing
for (int id : ids) {
System.out.print(id + ", ");
}
// outputs 1, 2, 3, 4, 5, 6,
我可以问一下为什么吗?这对我来说似乎是个坏主意:你会重用一个以前用于另一个对象的ID,这可能会导致混乱,很难快速实现,而且你不会得到任何东西:一个ID通常必须是唯一的,仅此而已。那些东西是什么?它们存放在哪里?如何删除它们?这是我需要完成的任务,就像学校的作业一样。。。