import java.util.*; import java.io.*; public class DictionaryAny { public static void main(String[] args) throws IOException { PrintStream output = System.out; Scanner input = new Scanner(System.in); // Type of collection Collection dictionary = null; output.println("Choose a collection"); output.println("1. ArrayList"); output.println("2. LinkedList"); output.println("3. TreeSet"); output.println("4. HashSet"); int collectionType = input.nextInt(); if (collectionType == 1) { output.println("array list"); dictionary = new ArrayList(); } else if (collectionType == 2) { dictionary = new LinkedList(); } else if (collectionType == 3) { dictionary = new TreeSet(); } else { dictionary = new HashSet(); } final String DICT_NAME = "dictionary.txt"; Scanner dictionaryInput = new Scanner(new File(DICT_NAME)); while (dictionaryInput.hasNextLine()) { String word = dictionaryInput.nextLine().trim(); dictionary.add(word); } output.println(dictionary.size()); // ArrayList version of the dictionary to pick random words from final ArrayList WORDS = new ArrayList(dictionary); // random number generator to randomly pick words Random rng = new Random(); // Number of words and test output.print("Number of words to look up? "); String num = input.next().trim(); int numWords = Integer.parseInt(num); output.print("Number of tests to run? "); num = input.next().trim(); int numTests = Integer.parseInt(num); // Average time long sumTime = 0; for (int test = 0; test < numTests; test++) { long startTime = System.nanoTime(); for (int i = 0; i < numWords; i++) { int index = rng.nextInt(WORDS.size()); String word = WORDS.get(index); boolean isInDictionary = dictionary.contains(word); } long endTime = System.nanoTime(); sumTime += endTime - startTime; } output.printf("Average time : %,.0f ns%n", ((double) sumTime / numTests)); } }