Lab 14: Auto Complete - Tries and Hash Tables
Learning Outcomes
- Implement a map using a list of key-value entries.
- Implement a trie using a recursive tree structure.
- Compare a hash-backed search structure with list-backed and tree-backed structures.
- Reuse an interface and its tests across multiple implementations.
Overview
This lab completes the AutoCompleter project you developed in Lab 8.
You will add two more implementations of the AutoCompleter interface: a
Trie backed by your own ListMap and a HashTable backed by Java's HashSet.
You will integrate them into your existing graphical user interface and compare
the behavior of the different data structures.
Due: Tuesday, December 8 (Week 15). The separate Lab 15 report is due Friday, December 11 (Week 15). You will benchmark and analyze your completed project in that assignment; no benchmarking report is required for Lab 14.
The original video introductions cover the trie and hash table and analysis portions of the project. Use this assignment and its README as the authoritative requirements for Lab 14.
1. Build on Lab 8
Continue working from your Lab 8 IntelliJ project. Incorporate your instructor's feedback and copy the new starter files into your project. Do not replace your previous implementation files or your own JUnit tests with blank files.
All five AutoCompleter implementations must follow the same behavioral
contract:
- Constructors that accept a
List<String>initialize the auto completer with the unique words in that list. The initial list is assumed to contain non-null, non-empty words. A null list is rejected with anIllegalArgumentException. add(word)adds a new word and returnstrue. It returnsfalsefor a duplicate and throwsIllegalArgumentExceptionfor a null or empty word.size()returns the number of distinct words.exactMatch(target)returns whether the target is stored as a complete word. A null or empty target returnsfalse.allMatches(prefix)returns every stored word beginning with the prefix, without duplicates. A null prefix returns an empty array. An empty prefix returns all stored words.- Matching is case-sensitive for every implementation. Do not convert words or queries to lowercase within one implementation.
- The order of the elements returned by
allMatches()is not part of the common interface contract. getBackingClass()returns the fully qualified class name, without theclassprefix (for example,java.util.ArrayList).
Your existing list-backed implementations must still use the supplied list
as their backing list. The constructors of Trie and HashTable should
copy the words into their own data structures, rather than retaining that list.
2. ListMap
Implement a class ListMap<K,V> that implements the Map<K,V> interface.
It must have exactly one instance field:
private final List<Map.Entry<K, V>> entries;
A public no-argument constructor initializes entries to an empty ArrayList.
Implement the following methods according to their usual Map behavior:
| Method | Required behavior |
|---|---|
clear() | Remove every mapping. |
containsKey(Object key) | Return whether a mapping exists for the key. |
get(Object key) | Return the mapped value, or null if absent. |
entrySet() | Provide a set containing all key-value entries, so callers can iterate over them. |
isEmpty() | Return whether there are no mappings. |
put(K key, V value) | Insert a new mapping and return null, or replace an existing mapping and return its previous value. |
remove(Object key) | Remove and return the mapped value, or null if absent. |
size() | Return the number of mappings. |
Keys are compared using equals(), not ==. Null keys are not supported;
key-based operations must throw NullPointerException when given a null key.
Null values are permitted. Replacing an existing mapping must not increase
size().
Create your own nested class implementing Map.Entry<K,V>. Its key is fixed
when the entry is created; setValue() replaces the value and returns the
previous value. The entry's equals() and hashCode() should be consistent
with the Map.Entry contract.
The required use of entrySet() in this lab is iteration over the current
mappings. Supporting mutation through the returned set or keeping a previously
returned set synchronized with later changes is not assessed. The remaining
Map methods may throw UnsupportedOperationException.
ListMap.
The purpose of this class is to implement a simple map using a list of entries.
3. Trie
Implement the AutoCompleter interface using a trie data structure. A trie is a
tree in which each node may have any number of children. A word is represented
by following a sequence of character-labeled edges.

The trie in the figure contains the strings SHE, SELLS, SEA, SHELLS,
and BY. Each character is an edge to another node. The T or F within a
node indicates whether the path from the root to that node represents a stored
word. For example, SHE and SHELLS are stored words, but SHELL is only a
prefix of a stored word.
Each node is itself a Trie object. The class must contain at least these
private fields:
private boolean endsWord;
private final Map<Character, Trie> edges;
Initialize edges using your own ListMap<Character, Trie> implementation,
not a Java library map. You may add fields and private helper methods as needed.
Provide two public constructors:
Trie()constructs an empty trie. New child nodes can use this constructor.Trie(List<String> items)constructs a trie containing the supplied words.
Adding a word
To add BY, start at the root and look for an edge labeled B. If it does not
exist, add an edge that maps B to a new empty trie. Follow that edge and
repeat the process for Y. Mark the final node's endsWord field as true.
If the final node already marked the end of a word, no new word has been added. Remember that an existing path may represent only a prefix, so finding all the necessary edges is not sufficient to determine that a word is already stored.
Keep track of the number of distinct words so that size() does not need to
traverse the tree.
Exact matches
Follow the edges corresponding to the characters in the target word. The word is stored only if every edge exists and the final node marks the end of a word.
Prefix matches
First follow the edges corresponding to the prefix. If the prefix does not exist, there are no matches. Otherwise, traverse only the subtree rooted at that node, collecting complete words. Include the prefix itself if it is a stored word. An empty prefix starts the traversal at the root.
Use entrySet() to iterate over the outgoing edges. You should not scan the
whole dictionary to find words with a non-empty prefix.
The getBackingClass() method returns the fully qualified name of your
ListMap class (for example, jones.ListMap after refactoring the package).
4. HashTable
Implement the AutoCompleter interface using Java's HashSet. The class must
be called HashTable and must have the following single instance field:
private final HashSet<String> items;
Provide a public constructor HashTable(List<String> items) that initializes
the set with the supplied words. Implement all five AutoCompleter methods
using the HashSet as the backing structure.
Consider why a hash table supports efficient exact matching but does not
organize words by their prefixes. allMatches() will need to inspect the words
in the set to find matches for a prefix.
getBackingClass() returns java.util.HashSet.
5. Testing
Update your Lab 8 JUnit tests so that the common behavioral tests can be used
with all five implementations. The same tests should also work for both
ArrayList and LinkedList backing lists. Do not write a separate copy of
identical tests for each implementation.
Add tests for the required ListMap methods, including insertion, replacement,
removal, missing keys, null values, and iteration over entries. Make sure your
common AutoCompleter tests cover duplicate words, shared prefixes, words that
are also prefixes of other words, case-sensitive matching, empty and missing
prefixes, and the null/empty argument rules.
When checking the results of allMatches(), compare the contents of the arrays
without assuming a particular order. Check the backing class separately for
each implementation.
6. Graphical User Interface
Extend your existing Lab 8 interface to include timing results for both the
Trie and HashTable implementations. The layout may differ from the earlier
example, but all Lab 8 functionality must remain available.
- Load a selected dictionary once and initialize all five implementations with the same distinct words. Use independent backing lists for the ordered and unordered implementations.
- Continue to allow the ordered and unordered list backings to be switched
independently between
ArrayListandLinkedList. Switching one must not change the other or reread the dictionary from disk. - When the search field contains three or more characters, time
exactMatch()andallMatches()for all five implementations and display all ten timing results. UseAutoCompleter.format()to format the measured durations. - Display matches from any one implementation. The results should be identical regardless of which one is used, apart from ordering.
- Whenever fewer than three characters are present, display the entire dictionary and clear all timing fields. Update the display when text is inserted or deleted, including when the user pastes text.
- When a new dictionary is loaded, clear the search field and timing results and display the newly loaded dictionary.
- Handle dictionary-loading failures and other recoverable GUI errors with meaningful alerts. The program must remain usable. Searching before a dictionary has been loaded must not cause an exception.
Time only the requested AutoCompleter operations, not file loading, GUI updates, or formatting the timings.
7. Prepare for Lab 15
The starter files include a completed Benchmarker program for Lab 15. Add
the following provided static method to your existing AutoCompleter
interface so the benchmark program compiles:
static String getString(int length) {
if (length < 0) {
throw new IllegalArgumentException("Length cannot be negative");
}
final int alphabetSize = 26;
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
result.append((char) ('a' + ThreadLocalRandom.current().nextInt(alphabetSize)));
}
return result.toString();
}
Add import java.util.concurrent.ThreadLocalRandom; to the interface. This
provided method generates a string of the specified length containing randomly
selected lowercase letters; length zero produces an empty string.
Keep the supplied Benchmarker class in your project. You do not need to run
benchmarks, produce graphs, complete asymptotic analysis, or write a report
for Lab 14. These activities belong to Lab 15.
Development Checkpoints
Follow the incremental commit checklist in README.md and push each checkpoint
according to the due dates in Canvas:
- Commit 1: "Lab 8 Updated and Stubs" — before lab Week 14.
- Commit 2: "ListMap Tested" — by the end of lab Week 14.
- Commit 3: "HashTable Tested" — Friday Week 14.
- Commit 4: "Trie Tested" — Sunday Week 15.
- Commit 5: "GUI Complete" — Monday Week 15.
Final completion (DONE14): Tuesday Week 15.
By Tuesday, December 8 (Week 15), submit the completed AutoCompleter project, including
all five implementations, the updated GUI, your tests, and the provided
benchmarking infrastructure. Run the full test suite, remove the dashes from
D-O-N-E-14 in the README, commit that change, and push your commits. The Lab 15 report is a
separate deliverable and is not required to complete Lab 14.
Acknowledgement
This laboratory assignment builds on assignments developed by Dr. Chris Taylor.