-1

The method generateId allocate ids to students,the method storeStudent is called by the method readData which reads data, the StudentId field in the data are all set to unknown so the method storeStudent replace the word unknown by a unique a id for each student but the problem with it if i have more than 10 student it will repeat the same ids again and I am trying to avoid the id duplication so how can i solve this problem

public void storeStudnet(Student student) {

        student.setId(generateCustomerId("AB-",1));

         for(Student students : studentList)
        {
        if(student.getStudentID().equals(student.getStudentID()))
         {
             student.setId(generateId("AB-",1));
         } 

        }

}
  studentList.add(student);
 }


   public String generateId(int numberaOfDigits)
{
    Random random = new Random();
    for(int i=0;i<numberaOfDigits;i++)
    {

       random.nextInt(9);  

    }

    return  random.nextInt(9);
} 
Alan Moore
  • 73,866
  • 12
  • 100
  • 156

2 Answers2

0

If you're using a DB for this and an ORM such as Hibernate, you already have annotations (@Id) that will take care of that.

If you want to create it yourself, you might want to use a synchronized method that takes care of always incrementing the id. Random is not a good option, nothing guarantees that it won't choose an already existing number (check the Random API).

0

I think the best solution is as in the comment keep incrementing the number. But If this does not go according to your requirement you can keep a separate list of generated id's and check if the id had been generated or not using list.contains(). A sample could be like this:

ArrayList<int> id = new ArrayList<int>() ;
Random random = new Random();
public int generateId(int numberaOfDigits)
{
  int x = random.netxInt(number);
  while(id.contains(x))
       {
        x = random.nextInt(number)
        }
  return x;
}

Also, There are some mistakes in your posted code:

  1. You return an int in generateId() but you defined the return type String.
  2. I am not sure what you trying to do with the for loop in the generateId() but it is not doing anything accept generating new random number which is not even stored anywhere.
Denis
  • 1,219
  • 1
  • 10
  • 15