在Java中,给对象编号的一种简单方法是什么?

huangapple go评论124阅读模式
英文:

In Java, what would be an easy way to number objects?

问题

第一个创建的对象在创建时知道它是"对象 1"。

第二个创建的对象在创建时知道它是"对象 2",依此类推。

英文:

e.g

the first object created knows that it is "object 1" when created.

the second object created knows that it is "object 2" when created etc.

答案1

得分: 5

这确实取决于使用情况,以下对于大多数情况可能不是一个好的解决方案。

但总的来说,你可以使用一个静态成员变量并在构造函数中进行递增:

public class Example {
    private static int counter = 0;
    private final int id;

    public Example() {
        id = counter++;
    }
}

需要注意的是,这也会在应用程序多线程时导致同步问题:一般来说,并发更新这个静态变量是不安全的。要修复这个问题,需要使用synchronized方法来递增变量,或将其声明为AtomicInteger

英文:

It really depends on the use-case, and the following is probably not a good solution for most of them.

But in general you can use a static member variable and increment it in the constructur:

public class Example {
    private static int counter = 0;
    private final int id;

    public Example() {
        id = counter++;
    }
}

Note that this also causes synchronisation problems once your application is multi-threaded: in general it is not safe to update this static variable concurrently. To fix this would require either using a synchronized method to increment the variable, or declaring it as an AtomicInteger.

答案2

得分: 0

你可以保留一个内部静态计数器(nextId)作为序列生成器,并使用实例字段来保存每个对象的值:

public class OrderedObject {
    private static int nextId = 1;
    private int id = nextId++;

    public int getOrder() {
        return id;
    }

    public String toString() {
        return "OrderedObject-" + id;
    }
    public static void main(String args[]) {
        System.out.println(new OrderedObject());
        System.out.println(new OrderedObject());
        System.out.println(new OrderedObject());
    }
}
英文:

You can keep an internal static counter(nextId) as asequence generator and an instance field to keep the value per object:

public class OrderedObject {
    private static int nextId=1;
    private int id=nextId++;
    
    public int getOrder() {
        return id;
    }

    public String toString()
    {
    	return "OrderedObject-"+id;
    }
    public static void main(String args[])
    {
    	System.out.println(new OrderedObject());
    	System.out.println(new OrderedObject());
    	System.out.println(new OrderedObject());
    }
    
}

huangapple
  • 本文由 发表于 2020年9月14日 15:35:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63879947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定