CS 1301 * Ch 6, Handout 1

advertisement
CS 1302 – Ch 23, TreeSets
In Class Exercise 2
Do this tutorial in class. First, there is a brief set of notes we will go over in class. Next, there are two
problems. The first is a step-by-step tutorial. The second is a problem you will work out the solution to.
This is to be turned in at a later date.
TreeSet Notes
1. A TreeSet is similar to a HashSet except that it is sorted. If the elements to be stored in the TreeSet are
primitive data types, then they will be sorted on their natural ordering. If the elements are objects
from a custom class, then the class must implement the Comparable interface. With custom objects,
there is a third technique we will consider later, the Comparator interface.
2. Why do we use TreeSet: it is fast at adding, removing, and seeing if an item is in the set (contains). And,
it has some new methods:
1
Problem 1 - TreeSet
1. Follow the steps below to complete the tutorial on TreeSet. Create a class called:
TreeSetExample1.java. Add this import: import java.util.*;
2. Create TreeSet from a HashSet – We can create a TreeSet just as we did a HashSet. However, we can
also create a TreeSet from a HashSet. To demonstrate this, first create a HashSet of Strings. Then, pass
the HashSet to the constructor of TreeSet. Notice that the Strings will be sorted. Add the code on the
left below. Run and observe output.
Code
// Create a hash set
Set<String> set = new HashSet<String>();
Output
// Add strings to the set
set.add("London");
set.add("Paris");
set.add("New York");
set.add("New Brunswick");
set.add("San Francisco");
set.add("Beijing");
set.add("New York");
// Create TreeSet from HashSet
TreeSet<String> treeSet =
new TreeSet<String>(set);
[Beijing, London, New Brunswick, New
York, Paris, San Francisco]
System.out.println( treeSet );
3. Try out the first and last methods. As the name implies, the methods return the first and last elements
in the TreeSet, respectively. Add the code on the left below. Run and observe output.
Code
String first = treeSet.first();
System.out.println("first(): " + first );
Output
Beijing
String last = treeSet.last();
System.out.println("last(): " + last );
San Francisco
2
4. Try out headSet, tailSet, and subSet methods. The headSet method takes a key and returns the Set of
elements that are before the key. The tailSet method takes a key and returns the Set of elements that
are equal to or after the key. Finally, the subSet method takes two keys and returns the Set of elements
that are greater than or equal to the first key and before the second key Add the code on the left
below. Run and observe output.
Code
// Returns a view of the portion of this set
// whose elements are strictly less than
// toElement, {x|x<e}
SortedSet<String> hSet = treeSet.headSet("New York");
Output
System.out.println("headSet(\"New York\"): " + hSet );
[Beijing, London, New
Brunswick]
// Returns a view of the portion of this set
// whose elements are greater than or equal
// to fromElement, {x|x>=e}
SortedSet<String> tSet = treeSet.tailSet("New York");
System.out.println("tailSet(\"New York\"): " + tSet );
[New York, Paris, San
Francisco]
SortedSet<String> tSet2 = treeSet.tailSet("New");
System.out.println("tailSet(\"New\"): " + tSet2 );
// Returns a view of the portion of this set
// whose elements range from fromElement,
// inclusive, to toElement, exclusive. x|e1<=x<e2}
SortedSet<String> sSet =
treeSet.subSet("London", "New York");
System.out.println("subSet(\"London\", \"New York\"): "
+ sSet );
[New Brunswick, New York,
Paris, San Francisco]
[London, New Brunswick]
5. Try out lower and higher methods. Instead of a set, these methods return a single element. The lower
(higher) method takes a key and returns the element that is strictly less than (greater than) than the
key. Add the code on the left below. Run and observe output.
Code
// Returns the greatest element in this set strictly less
// than the given element, or null if there is no such
// element, x<e
String lower = treeSet.lower("P");
System.out.println("lower(\"P\"): " + lower );
Output
New York
// Returns the least element in this set strictly greater
// than the given element, or null if there is no such
// element, x>e
String higher = treeSet.higher("P");
System.out.println("higher(\"P\"): " + higher );
Paris
String higher2 = treeSet.higher("Paris");
System.out.println("higher(\"Paris\"): " + higher2 );
San Francisco
3
6. Try out floor and ceiling methods. These are similar to lower and higher, except that they include
equality. For instance, floor returns the element that is less than or equal to the key. Add the code on
the left below. Run and observe output.
Code
// Returns the greatest element in this set less than or
// equal to the given element, or null if there is no such
// element, x<=e
String floor = treeSet.floor("P");
System.out.println("floor(\"P\"): " + floor );
Output
New York
String floor2 = treeSet.floor("Paris");
System.out.println("floor(\"Paris\"): " + floor2 );
Paris
// Returns the least element in this set greater than or
// equal to the given element, or null if there is no such
// element, x>=e
String ceiling = treeSet.ceiling("P");
System.out.println("ceiling(\"P\"): " + ceiling );
Paris
String ceiling2 = treeSet.ceiling("Paris");
System.out.println("ceiling(\"Paris\"): " + ceiling2 );
Paris
7. Try out the iterators: iterator and descendingIterator. Note that the TreeSet class has a
descendingIterator that iterates over the TreeSet in reverse order. Add the code on the left below. Run
and observe output.
Code
Iterator<String> i = treeSet.iterator();
while( i.hasNext() )
System.out.print( i.next() + ", " );
Output
London, New Brunswick, New
York, Paris,
i = treeSet.descendingIterator();
while( i.hasNext() )
System.out.print( i.next() + ", " );
Paris, New York, New
Brunswick, London,
4
Problem 2
1. Download the two test files from the web: dw.txt and jk.txt
2. Create a new class, TreeSetProblems.java. Write the following methods and a main to test them.
3. Write these methods:
a. An ArrayList stores Integers. Write a method, getGreaterOrEqual, that accepts the ArrayList and an
integer “key”. The method should return a SortedSet of numbers greater than or equal to the key.
Hint: Look at a TreeSet constructor that accepts a Collection.
b. You have two ArrayLists of Integers. Write a method, getGreater2 that accepts the two ArrayLists
and an integer “key”. The method will return a SortedSet of all numbers from either list that are
greater than or equal to the key.
c. A store collected id’s from customers. Then they did the same at another location. The id’s are
stored in two ArrayLists. Write a method, getDuplicatesIDs that takes the two ArrayList’s and
returns a SortedSet of the duplicate id’s.
Hint: Draw an example and work by hand.
d. One ArrayList contains the names of people on a ballot. Another ArrayList contains the votes for
people on the ballot. A vote is represented by the name of the person being voted for. For
example:
Candidates: { zena, earl, herb, ann }
Votes: { earl, earl, ann, earl }
Write a method, getNoVotes that takes the candidate and votes ArrayLists and returns a SortedSet
of people who did not receive a vote. From the example above, the return would be: { herb, zena }.
e. An ArrayList stores strings. Write a method, removeWithChar that accepts the ArrayList and a
character. The method should return a SortedSet of only the words that do NOT begin with the
character. No String/Character functions allowed.
Hint: This will take two steps.
Hint: How do you find the words that begin with the character?
Hint: How do you remove those words?
5
f. Write a method, findBetween that takes an ArrayList of strings and two string keys. The method will
return a SortedSet of all the unique strings between the two keys, inclusive. In other words, if the
keys are “d” and “f” then all strings that begin with “d” or “e”, or the string “f” itself should be
returned. Examples:
Ordered unique words: { abe, d, dame, emy, f, fred, xav, zed }
findBetween(“d”,”f”) returns: { d, dame, emy, f }
findBetween(“fred”,”zed”) returns: { fred, xav, zed }
findBetween(“a”,”dam”) returns: { abe, d }
Hint: study these methods: headMap, tailMap, subMap, first, last, lower, higher, ceil, floor. You
need two of these.
Hint: If you get the first example above to work, unless you have thought carefully, the second
example will fail.
6
Download