Sets in Java
HashSet and TreeSet
HashSet and TreeSet implement the Set interface, and the idea of a Set in Java is modelled off of the idea of a set in Math. A Set simply contains a bunch of objects. You must be able to determine if a given object is in a Set. For this reason, a Set cannot contain duplicates. Contrast this point with a List which can contain duplicates. Also, a Set is not ordered. It's just a bunch of non-repeating objects grouped together.
Below is an example illustrating the use of Set including the fact that duplicates are not allowed
SetDemo.java
import java.util.*;
public class SetDemo {
public static void main(String[] argv) {
//+
Set h = new HashSet();
h.add("One");
h.add("Two");
h.add("One"); // DUPLICATE
h.add("Three");
Iterator it = h.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
//-
}
}
So what's the difference between HashSet and TreeSet? Compile and run the HashTreeSetDemo class below first and try to see a difference.
HashTreeSetDemo.java
import java.util.*;
public class HashTreeSetDemo {
public static void main (String args[]) throws Exception {
String hashElements[] = {"a", "b", "z","c"};
Set hashSet = new HashSet();
for (int i=0, n=hashElements.length; i<n; i++) {
hashSet.add(hashElements[i]);
}
Iterator hashItr = hashSet.iterator();
while(hashItr.hasNext())
System.out.println(hashItr.next() );
System.out.println("*************");
String elements[] = {"a", "b", "z","c"};
Set set = new TreeSet();
for (int i=0, n=elements.length; i<n; i++) {
set.add(elements[i]);
}
Iterator it = set.iterator();
while(it.hasNext())
System.out.println(it.next() );
}
}
As you might be able to tell the main difference between TreeSet and HashSet has to do with how the elements in the set are ordered. A HashSet uses a HashTable
Programming Projects
- Project 1) Create a class called ExtendedSet that has the following methods
- difference() : This mehtod would take a set as a parameter and subtract the contents of that set from the current set if they exist in the currentset. The returned result would be a new set.
- intersection() : this method would take a set as aparamter and would return a set containing those elements that exist in both sets.
Top
|