/******************************************************************************
* Compilation: javac HashSET.java
* Execution: java HashSET
* Dependencies: none
*
* Set implementation using Java's HashSet library.
* Does not allow duplicates.
*
******************************************************************************/
import java.util.HashSet;
import java.util.Iterator;
/**
* This class represents an unordered set.
* It supports the usual add, contains, and remove
* methods.
*
* This implementation uses a hash table.
* The add, contains, and remove
* methods take constant time on average under the uniform hashing assumption.
*
* For additional documentation,
* see Section 4.4 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*/
public class HashSET implements Iterable {
private HashSet set;
/**
* Create an empty set.
*/
public HashSET() {
set = new HashSet();
}
/**
* Is this set empty?
*/
public boolean isEmpty() {
return set.isEmpty();
}
/**
* Add the key to this set.
*/
public void add(Key key) {
set.add(key);
}
/**
* Does this set contain the given key?
*/
public boolean contains(Key key) {
return set.contains(key);
}
/**
* Remove the given key from this set.
*/
public void remove(Key key) {
set.remove(key);
}
/**
* Return the number of keys in this set.
*/
public int size() {
return set.size();
}
/**
* Return an Iterator for this set.
*/
public Iterator iterator() {
return set.iterator();
}
/**
* Return the union of this set with that set.
*/
public HashSET union(HashSET that) {
HashSET c = new HashSET();
for (Key x : this)
c.add(x);
for (Key x : that)
c.add(x);
return c;
}
/**
* Return the intersection of this set with that set.
*/
public HashSET intersects(HashSET that) {
HashSET c = new HashSET();
if (this.size() < that.size()) {
for (Key x : this) {
if (that.contains(x)) c.add(x);
}
}
else {
for (Key x : that) {
if (this.contains(x)) c.add(x);
}
}
return c;
}
/***************************************************************************
* Test routine.
***************************************************************************/
public static void main(String[] args) {
HashSET set = new HashSET();
// insert some keys
set.add("www.cs.princeton.edu");
set.add("www.cs.princeton.edu"); // overwrite old value
set.add("www.princeton.edu");
set.add("www.math.princeton.edu");
set.add("www.yale.edu");
set.add("www.amazon.com");
set.add("www.simpsons.com");
set.add("www.stanford.edu");
set.add("www.google.com");
set.add("www.ibm.com");
set.add("www.apple.com");
set.add("www.slashdot.com");
set.add("www.whitehouse.gov");
set.add("www.espn.com");
set.add("www.snopes.com");
set.add("www.movies.com");
set.add("www.cnn.com");
set.add("www.iitb.ac.in");
StdOut.println(set.contains("www.cs.princeton.edu"));
StdOut.println(!set.contains("www.harvardsucks.com"));
StdOut.println(set.contains("www.simpsons.com"));
StdOut.println();
// print out all keys in the set
for (String s : set) {
StdOut.println(s);
}
}
}