TreeSet
The next collection class we will look at is the TreeSet class. You will learn much more about
the structure of this class (and tree structures in general) in CIS 300, but for now, all you need to
know is that a TreeSet is an efficient way to store data that needs to be sorted. This data is NOT
stored in a linear way (like an array, with one element after the other), so it will be trickier for us
to look at all the elements.
Creating a TreeSet
To create a TreeSet object, we do:
TreeSet<type> name = new TreeSet<type>();Here, type is the type of elements we want to store, and name is the variable name we’re
giving to this TreeSet. For example, to create a TreeSet that holds a bunch of names in
sorted order, we might do:
TreeSet<String> namesTree = new TreeSet<String>();Adding elements
Once we’ve created a new TreeSet object, we can add elements to it. This is done with the
syntax:
name.add(elem);Where name is the name of our TreeSet, and elem has the same type we specified when
creating that tree. For example, we could add names to our namesTree object as follows:
namesTree.add("Fred");
namesTree.add("Amy");
namesTree.add("Sam");
namesTree.add("Katelyn");Again, a TreeSet does not store elements the way you would expect them to be stored in
arrays (with indices corresponding to the different elements). Instead, the elements are stored in
sorted order. To get them back, we will need to use either an Iterator or a for-each loop.
Iterator
We can use an iterator to access all the elements in our TreeSet in sorted order. Suppose we
have the namesTree TreeSet from above. We can access and print each name like this:
Iterator<String> it = namesTree.iterator();
while (it.hasNext())
{
String cur = it.next();
System.out.println(cur);
}This will print:
Amy
Fred
Katelyn
SamFor-each loop
We can also iterate over the elements in a TreeSet using a for-each loop, because, as we learned in the previous section, a for-each loop over a collection is automatically translated by the compiler to a while loop with a iterator.
For example, we can rewrite the previous while loop that used an iterator to print all the names in the TreeSet using a for-each loop:
for (String cur : namesTree)
{
System.out.println(cur);
}Removing elements
We can remove elements from our TreeSet by passing in which object we want to remove.
The remaining elements in the TreeSet are shifted around to still be in sorted order. The
syntax is:
name.remove(obj)Where obj is the element we wish to remove. This method does return the whether or not it
found that element (boolean) so you can optionally store the result of the method call.
For example, we can do:
namesTree.remove("Katelyn");To remove “Katelyn”. If we were to print each element again, using an iterator or a for-each loop, it would print:
Amy
Fred
SamNotice that it would shift around the elements to still be sorted after removing “Katelyn”.