Created
December 16, 2013 16:00
-
-
Save llbit/7989415 to your computer and use it in GitHub Desktop.
Find String hash collisions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.io.*; | |
/** | |
* Find String hash collisions. | |
* @author Jesper Öqvist <[email protected]> | |
*/ | |
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