How to generate sequential ID?

Asked

Viewed 1,338 times

-1

I’m trying to generate a sequential ID for each user registered on the system, but all users leave with the same ID number generated.

public class User {  
    // ...  
    int id=1;  
    public void gerarid() {  
        id++;  
    }  
    // ...
}

public class Mein {  
    public static void main(String[] args) {  
        User u1 = new User();  
        // ...  
        u1.gerarid();  
        // ...  
    }  
}  
  • You need to capture the generated ID number, or the highest number and add 1 from it. What happens in your code is that each time the script is executed you put the id as 1.

2 answers

1

Just turn the field id in static. The keyword static indicates to the compiler that instead of creating a field in an instance you want to create a field in a class.

class User {  

        // Unica mudança significativa no código.
        static int id;  

        public void gerarid() {  
            id++;  
        }  

}

public class Main {    


    public static void main(String[] args) {  
        User u1 = new User();  

        // Gera 10 Ids e os imprime
        for (int i = 0;i < 10 ;i++ ) {
           u1.gerarid();  
           System.out.println(u1.id);
        }

    }  
}  

0


To every user you create, you’re saying that the id of it one is 1. That’s because the command int id = 1 is within the class User, and the method gerarid(), which is also within the class, will only increase the id of User which method gerarid() belongs, for example:

User u1 = new User(); // u1 possui um atributo chamado id (u1.id) com o valor 1 
User u2 = new User(); // u2 possui um atributo chamado id (u2.id) com o valor 1
u1.gerarid();

By calling u1.gerarid(), the instruction id++ is increasing the id of User u1, unrelated to u2, much less with your id (u2.id). The result of the above code would be:

u1.id: 2 // O id de u1 foi incrementado ao chamar u1.gerarid()
u2.id: 1 // Não foi alterado

To solve your problem, you need a variable that does not belong to a User, this variable will save the id that the next User to be created must have:

public class User {  
    // ...  
    int id; // Receberá o valor de contadorDeId
    // ...
}

public class Mein {  
    public static void main(String[] args) {
        int contadorDeId = 1;
        User u1 = new User();
        u1.id = contadorDeId++; // Atribui e depois incrementa contadorDeId para 2

        // ...  

        User u2 = new User();
        u2.id = contadorDeId++; // Atribui e depois incrementa contadorDeId para 3...
    }  
}

With this, you don’t need the method gerarId(), at least not within the class User. You can use the concept of builders to assign the id every new User in a more elegant way.

  • Valeuu, your method is much simpler and I hindered kkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.