/** * Title: MapPlay * Description: Comparison of HashMaps and TreeMaps * * counts word frequencies in a text file using a map * @author hollingd@cs.rpi.edu */ import java.util.*; import java.io.*; /** *
CountWords is a demonstration class used for comparing the performance of * HashMap and TreeMap classes with respect to the lookup of map elements.
* *The main() method builds a hashmap containing the word frequiences of * a file named on the command line, then performs many map accesses * (a random sequence of accesses). The accesses are timed and the result * is printed out. The entire process is then repeated, but the second time * using a TreeMap instead of a HashMap.
*/ public class CountWords { static final int NUM_ACCESSES=100000; Map words; // Constructor takes a map object CountWords(Map w) { words = w; } // countWordsInFile reads from a file and counts the frequency of each word // found in the file. uses the map words to keep track of // the count. // // assumes that map named words already exists! void countWordsInFile(String filename) throws IOException { BufferedReader in = new BufferedReader( new FileReader(filename)); String s = in.readLine(); while (s != null) { // split the line in to words String[] tokens = s.split("[^a-zA-Z0-9]"); for (int i=0;i