有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

唯一键为每个java对象实例生成尽可能低的ID号

我想按照以下规则为对象生成ID号: 每个新对象将获得一个唯一的ID号(第一个ID号为1), 然后每个新对象将获得最低的可用ID号

例如,如果我声明4个对象 对象1 ID:1 对象2 ID:2 对象3 ID:3 对象4 ID:4

然后,如果我删除对象编号3。 因此,将生成的下一个对象将获得ID:3,而不是5

使用ID生成器的最佳方法是什么


共 (3) 个答案

  1. # 1 楼答案

    您可以使用ConcurrentHashMap<Integer, Boolean>来设置要使用的唯一ID。使用Boolean值检查它们是否被使用。然后,使用ConcurrentHashMap<YourObject, Integer>将所需对象存储在其相关ID内。因此,必须手动同步两个结构中的添加/删除,以始终定义可用的最低键

    请注意,拥有所有这些都是非常昂贵和难以维护的。最好使用第三方元素(可能是嵌入式数据库?)为你解决所有这些问题

  2. # 2 楼答案

    我想你想用Java来做。我建议如下:

    1. 具有用于为实体提供ID的序列。它非常简单,我认为不需要详细解释——它只返回1、2、3等。

    2. 现在我们需要处理删除。连同我建议的序列,有一个SortedSet的ID被删除,可以分配给新的实体

    3. 将这两个结构结合在一起,表现为:

      • 如果集合不是空的,则返回其第一个值并将其从集合中移除。它将是最低的值,因为您使用SortedSet

      • 如果为空,只需返回序列中的下一个数字

    当然,您需要处理这个操作的原子性,并且可能会遇到并发问题,但对于这个问题,详细讨论它有点离题

  3. # 3 楼答案

    注意:这是我的方式,因为我不知道列表。如果有一个列表可以在没有算法的情况下完成这个问题,那就太好了。不要因为我的答案没有必要就投反对票

    我想你可以有一个ArrayList,只需从中添加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
    }
    

    所以我所做的就是创建一个列表,其中id的值为正值,而在以前有id但现在不再有id的地方有负值。这样做的原因是,如果列表中的值为负数,我们可以直接替换它。例如:

    // 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,