您需要一个 静态的 类成员来跟踪上次使用的索引。确保还实现一个复制构造函数:
class students{ private static int next_id = 0; // <-- static, class-wide counter private int id; // <-- per-object ID private String name; public students(String name) { this.id = ++students.next_id; this.name = name; // ... } public students(students rhs) { this.id = ++students.next_id; this.name = rhs.name; // ... } public static void reset_counter(int n) // use with care! { students.next_id = n; } // ...}更新: 正如@JordanWhite建议的那样,您可能希望使static计数器成为 atomic
,这意味着可以安全地同时使用(即一次在多个线程中使用)。为此,将类型更改为:
private static AtomicInteger next_id = new AtomicInteger(0);
增量读取和复位操作变为:
this.id = students.next_id.incrementAndGet(); // like "++next_id"students.next_id.set(n); // like "next_id = n"



