-3

when storing to student may happen to have the same id, so how can i avoid the duplication, I have tried the while loop and the for each loop but it did not work

public void addStudent(Student student)

{

student.setId(ganerateNewRandom("aa", 2));

students.add(student);

}






  public String ganerateNewRandom(String prefix, int number)
 {

  Random random = new Random();

    StringBuffer ret = new StringBuffer(prefix);


    for(int i=0;i<number;i++) ret.append(random.nextInt(10));


    return ret.toString();


}
Ghassar Qhasar
  • 75
  • 1
  • 11

5 Answers5

5

I suggest you just imitate the way it is done in databases: Start with id=1 and each time enlarge it by 1: id++. That way each student will have unique id and you don't have to generate random numbers.

Martinsos
  • 1,598
  • 14
  • 26
3

Use java.util.UUID to generate proper unique ID.

example:

UUID myID = UUID.randomUUID();

It uses RFC 4122: A Universally Unique IDentifier (UUID) URN Namespace" methodology.

user1697575
  • 2,759
  • 1
  • 20
  • 34
  • Nice tips! well i suppose they still exists a tiny chance to get a duplicate isn't it ? – Gab Mar 28 '13 at 16:15
  • @Gab Its pretty solid and standard practice for UID generation in Java. Refer to RFC 4122 to get more information. – user1697575 Mar 28 '13 at 16:19
  • Wikipedia: "In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%." – Louis Wasserman Mar 28 '13 at 16:47
2

Just tell me all of this is not used to generate a database id. if it's the case you are going the worst way, id generation MUST be delegated to the database

Gab
  • 7,071
  • 2
  • 32
  • 62
1

To make sure your random numbers are unique you must store all previous random numbers.

How you store them depends on how many you plan to generate.

OldCurmudgeon
  • 60,862
  • 15
  • 108
  • 197
1

I would recommend checking out Google's repository with regards to random number generation here

david99world
  • 18,271
  • 28
  • 102
  • 127