就像您提到
static int的ID一样,在创建新对象时将其递增。
class MyObject { private static int counter = 0; public final int objectId; MyObject() { this.objectId = counter++; }}请注意,
counter++如果
MyObject由多个线程创建,则需要保护(例如
AtomicInteger,根据其他答案的建议使用)。

就像您提到
static int的ID一样,在创建新对象时将其递增。
class MyObject { private static int counter = 0; public final int objectId; MyObject() { this.objectId = counter++; }}请注意,
counter++如果
MyObject由多个线程创建,则需要保护(例如
AtomicInteger,根据其他答案的建议使用)。