Skip to content

Instantly share code, notes, and snippets.

@llbit
Created December 16, 2013 16:00
Show Gist options
  • Save llbit/7989415 to your computer and use it in GitHub Desktop.
Save llbit/7989415 to your computer and use it in GitHub Desktop.
Find String hash collisions.
import java.util.*;
import java.io.*;
/**
* Find String hash collisions.
* @author Jesper Öqvist <jesper.oqvist@cs.lth.se>
*/
public class StringHash2 {
public static void main(String[] args) {
Map<Integer,Collection<String>> map = new HashMap<>();
Scanner scanner = new Scanner(System.in);
int numLines = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
numLines += 1;
int hash = line.hashCode();
Collection<String> lines = map.get(hash);
if (lines == null) {
lines = new LinkedList<String>();
lines.add(line);
map.put(hash, lines);
} else {
lines.add(line);
}
}
for (Map.Entry<Integer,Collection<String>> group : map.entrySet()) {
Collection<String> lines = group.getValue();
if (lines.size() > 1) {
System.out.println("" + group.getKey() + ":");
for (String line: lines) {
System.out.println("\t" + line);
}
}
}
System.out.println("Num hash codes: " + map.keySet().size());
System.out.println("Num lines: " + numLines);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment