Java Reference
In-Depth Information
5. It would make more sense to make it a derived class of the ArrayList<T> class.
Then the elements are ordered. You can ensure against repeated elements by
redefining all methods that add elements so that the methods check to see if the
element is already in the class before entering it. A derived class of the HashSet<T>
class would automatically ensure that no element is repeated, but it would seem to
take a good deal of work to maintain the elements in order.
6. The Customer class must override hashCode and equals . A simple technique
to implement hashCode when the class contains strings is to return the string's
hashCode method. One possible implementation of these methods follows.
public int hashCode()
{
return this.toString().hashCode();
}
public boolean equals(Object obj)
{
Customer other = (Customer) obj;
return (other.toString().equals(this.toString());
}
7. Multiple copies of some element are not allowed as a key, but are allowed as values.
8. The variable would be defined as
HashMap<Integer,Employee> employeeMap =
new HashMap<Integer,Employee>(100);
If the ID numbers are between 0 and 100, then the map will work, but a simple
array or ArrayList might be a more appropriate data structure.
9. A HashSet<T> does not. An ArrayList<T> does.
10. The answer to both questions is the same: They will return the same element.
Programming Projects
Visit www.myprogramminglab.com to complete select exercises online and get instant
feedback.
1. Redo Programming Project 6.8 in Chapter 6, but this time do it for a vector of
strings to be sorted into lexicographic order.
2. The Sieve of Erastothenes is an ancient algorithm that generates prime numbers.
Consider the list of numbers from 2 to 10 as follows:
2
3
4
5
6
7
8
9
10
The algorithm starts with the first prime number in the list, which is 2, and then
iterates through the remainder of the list, removing any number that is a multiple
of 2 (in this case, 4, 6, 8, and 10), leaving
2
3
5
7
9
 
Search WWH ::




Custom Search