java 创建的对象的 ID 生成器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7660409/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:52:06  来源:igfitidea点击:

ID generator for the Objects created

javaobjectconstructor

提问by arjacsoh

I need a class which creates Objects assigning an ID to each Object created. This ID is as usual an int attribute to the class. I want this value (ID) to be increased each time an Object is created and then to be assigned to that Object starting with 1. It strikes me that I need a static int attribute.

我需要一个创建对象的类,为每个创建的对象分配一个 ID。该 ID 通常是该类的一个 int 属性。我希望每次创建对象时都会增加此值 (ID),然后将其分配给从 1 开始的对象。这让我觉得我需要一个静态 int 属性。

How can I initialize this static attribute?

如何初始化这个静态属性?

Should I create a separate method to do the increment of the ID (as an ID generator) which is invoked inside the constructor?

我应该创建一个单独的方法来增加在构造函数中调用的 ID(作为 ID 生成器)吗?

What is in general the most effective and well-designed manner to implement that?

一般来说,实现这一目标的最有效和设计最完善的方式是什么?

采纳答案by dacwe

Just like you mention use a static intfor the id, and increment it when creating new objects.

就像你提到的使用static intid 一样,并在创建新对象时增加它。

class MyObject {

    private static int counter = 0;

    public final int objectId;

    MyObject() {
        this.objectId = counter++;
    }
}

Please note that you need to protect counter++if MyObjectis created by multiple threads (for example using AtomicIntegeras the other answers suggest).

请注意,counter++如果MyObject是由多个线程创建的,则需要保护(例如AtomicInteger,按照其他答案的建议使用)。

回答by Andreas

You could also try java.util.concurrent.AtomicInteger, which generates IDs in

你也可以尝试 java.util.concurrent.AtomicInteger,它在

  1. a atomic way and
  2. sequential
  1. 一种原子方式和
  2. 连续的

You may use this in a static context like:

您可以在静态上下文中使用它,例如:

private static final AtomicInteger sequence = new AtomicInteger();
private SequenceGenerator() {}

public static int next() {
    return sequence.incrementAndGet();
}

回答by Barmaley Red Star

I would suggest to use AtomicInteger, which is thread-safe

我建议使用AtomicInteger,这是线程安全的

class MyObject
{
    private static AtomicInteger uniqueId=new AtomicInteger();
    private int id;

    MyObject()
    {
       id=uniqueId.getAndIncrement();
    }

}