英文:
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());
    }
    
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论