How to generate unique ID that is integer in java that not guess next number?
int uniqueId = 0;
int getUniqueId()
{
return uniqueId++;
}
Add synchronized
if you want it to be thread safe.
Just generate ID and check whether it is already present or not in your list of generated IDs.
import java.util.UUID;
public class IdGenerator {
public static int generateUniqueId() {
UUID idOne = UUID.randomUUID();
String str=""+idOne;
int uid=str.hashCode();
String filterStr=""+uid;
str=filterStr.replaceAll("-", "");
return Integer.parseInt(str);
}
// XXX: replace with java.util.UUID
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(generateUniqueId());
//generateUniqueId();
}
}
}
Hope this helps you.
How unique does it need to be?
If it's only unique within a process, then you can use an AtomicInteger and call incrementAndGet() each time you need a new value.
Do you need it to be;
Unique at any time:
int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);