fork(1) download
  1. import java.nio.charset.StandardCharsets;
  2. import java.security.MessageDigest;
  3. import java.util.Base64;
  4. import java.util.HashSet;
  5.  
  6. class Test {
  7. public static void main (String[] args) throws java.lang.Exception {
  8.  
  9. HashSet<String> set = new HashSet<>();
  10. int count = 0;
  11. for (int i = 0; i < 1000000; i++) {
  12. if (!set.add(hash(""+i))) {
  13. count++;
  14. }
  15. }
  16. System.out.println("Number of collisions: " + count);
  17. }
  18.  
  19. static String hash(String str) throws Exception {
  20. MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
  21. byte[] digest = sha256.digest(str.getBytes(StandardCharsets.UTF_8));
  22. return Base64.getEncoder().encodeToString(digest).substring(0, 7);
  23. }
  24. }
  25.  
Success #stdin #stdout 2.5s 211436KB
stdin
Standard input is empty
stdout
Number of collisions: 0