Will java.util.UUID work for classes in Java? That is to say i have a class that requires a unique id such that each time i construct an object of that class inside the main method, it will have a unique ID number.
the constructor might look something like this:
class flight{
private UUID id;
public void flight(){
id = UUID.randomUUID();
}
}
and the main method call might look something like this:
public static void main(String[] args){
flight[] allflights = new flight[100];
flight tempFlight;
for(int i=0; i<100; i++){
tempFlight = new flight()
allflights[i] = tempFlight;
}
Will this generate a unique ID for all the flights inside the flight array?
Yes, this is what UUIDs are for. You’ll get a new random UUID every time you call randomUUID() ; a UUID is a 128bit value.
So theoretically you could get collisions when using random UUIDs, but as it says that a cryptographically strong random generator is used i don’t think you need to bother with that possibility.