The Set Interface
Reading Assignment for Oct 20:
The Collection Interface lesson in the Java Tutorial:
http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html
The Set interface lesson:
http://java.sun.com/docs/books/tutorial/collections/interfaces/set.html
Recall: A set is a collection that does not contain duplicate elements.
- The Set interface extends Collection.
- The Set interface contains no methods other than those
inherited from the Collection interface.
- It adds the restriction that no duplicates are permitted.
Two implementations of the Set interface in the JDK:
- HashSet - stores its elements in what is called a hash
table. This implementation usually provides the best performance.
Elements not in order.
- TreeSet - stores its elements in a red-black tree. This
implementation allows you to order the elements.
Note: I do not expect you to be familiar with hash tables and
red-black trees.
Example:
Collection coll = new ... ;
// Define a Collection that contains the elements in coll, but without
any duplicates
Collection noRepeats = new HashSet(coll);
Exercise: Write a program that takes some words on the command line and
prints a list of the words with duplicates removed.
import java.util.*;
public class FindDups
{
public static void main(String[] args)
{
// finish the
program
}
}
Exercise: Write a program that takes words on the command line and
prints 2 lists: one list containing all the words that occurred only
once, and another list with all the words that occurred more than once.
(Use 2 sets and the removeAll() method).
Note: If you used a HashSet, try using a TreeSet. If you used a
TreeSet, try your program with a HashSet.