Sets
}
return false;
}
Lastly, you’ve implemented the iterator() method to allow traversal of all the contained values. Here, you’ve used the HashtableIterator from Chapter 11. Note that this was possible because HashtableIterator is based on the Iterable interface, rather than a List.
Other than that, the only other thing you’ve done is add some convenience constructors for usability, but HashSet is pretty much a carbon copy of BucketingHashtable from Chapter 11.
Given the use of a hash table based on buckets, and assuming a good hash function in the form of the hashCode method on the values being stored, you can expect to achieve fairly close to O(1) performance. Of course, as noted at the start of this section, the use of hashing necessarily precludes any notion of ordering, so an iterator will appear to return the values randomly.
A Tree Set
Sets don’t usually guarantee an ordering of the data. Sometimes, though, you may need a predictable iteration order — for example, when displaying options from which a user selects, or maybe in an alphabetical list of names from an address book, all while maintaining set semantics. Binary search trees (see Chapter 10) provide exactly the data structure you need.
Before proceeding with the implementation of tree-based sets, we recommend that you revisit binary search trees to refresh your understanding of the core concepts and code because the discussion
will again be limited to only the differences between the TreeSet code presented and the original
BinarySearchTree code.
Try It Out |
Testing and Implementing a Tree Map |
Start by creating the TreeSetTest class as follows:
package com.wrox.algorithms.sets;
public class TreeSetTest extends AbstractSetTestCase { protected Set createSet() {
return new TreeSet();
}
}
Follow the class with the tree set implementation:
package com.wrox.algorithms.sets;
import com.wrox.algorithms.iteration.Iterator;
import com.wrox.algorithms.iteration.IteratorOutOfBoundsException; import com.wrox.algorithms.sorting.Comparator;
import com.wrox.algorithms.sorting.NaturalComparator;