Automatic id generation

后端 未结 3 645
我寻月下人不归
我寻月下人不归 2021-01-15 11:28

Any one have idea how to generate id starting from 1 so that the next object has 2 and so on?

I have trying the following but dose not work:

<         


        
3条回答
  •  萌比男神i
    2021-01-15 11:51

    You need a static class member to keep track of the last-used index. Be sure to also implement a copy constructor:

    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;
        }
    
        // ...
    }
    

    Update: As @JordanWhite suggest, you might like to make the static counter atomic, which means that it will be safe to use concurrently (i.e. in multiple threads at once). To that end, change the type to:

    private static AtomicInteger next_id = new AtomicInteger(0);
    

    The increment-and-read operation and the reset operation become:

    this.id = students.next_id.incrementAndGet();  // like "++next_id"
    
    students.next_id.set(n);                       // like "next_id = n"
    

提交回复
热议问题