Create a gist now

Instantly share code, notes, and snippets.

Empirically tests degree of uniqueness when converting UUIDs to hashcode values
package collisions.test;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class UUIDToHashcodeUniquenessTestMain {
private final static int num_of_users = 1000 * 1000;
private final static int num_of_stacks = 50;
public static void main(String[] args) {
int collisions = 0;
for (int i = 0; i < num_of_users; i++) {
collisions += calcCollisionsForUser();
}
System.out.println("Had " + collisions + " collisions for " + num_of_users + " users");
}
private static int calcCollisionsForUser() {
int collisions = 0;
Set<Integer> uuidSet = new HashSet<Integer>(num_of_stacks * 2);
for (int i = 0; i < num_of_stacks; i++) {
String uuid = UUID.randomUUID().toString();
Integer uuidHashcode = uuid.hashCode();
if (uuidSet.contains(uuidHashcode)) {
collisions++;
}
uuidSet.add(uuidHashcode);
}
return collisions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment