Skip to content

Instantly share code, notes, and snippets.

@llbit
Created December 16, 2013 16:00
Show Gist options
  • Select an option

  • Save llbit/7989415 to your computer and use it in GitHub Desktop.

Select an option

Save llbit/7989415 to your computer and use it in GitHub Desktop.

Revisions

  1. llbit created this gist Dec 16, 2013.
    38 changes: 38 additions & 0 deletions StringHash2.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    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);
    }
    }