Java Reference
In-Depth Information
3 public class TestTreeSetWithComparator {
4 public static void main(String[] args) {
5 // Create a tree set for geometric objects using a comparator
6 Set<GeometricObject> set =
7 new TreeSet<>( new GeometricObjectComparator());
8 set.add( new Rectangle( 4 , 5 ));
9 set.add( new Circle( 40 ));
10 set.add( new Circle( 40 ));
11 set.add( new Rectangle( 4 , 1 ));
12
13 // Display geometric objects in the tree set
14 System.out.println( "A sorted set of geometric objects" );
15 for (GeometricObject element: set)
16 System.out.println( "area = " + element.getArea());
17 }
18 }
tree set
display elements
A sorted set of geometric objects
area = 4.0
area = 20.0
area = 5021.548245743669
The GeometricObjectComparator class is defined in Listing 20.4. The program creates
a tree set of geometric objects using the GeometricObjectComparator for comparing the
elements in the set (lines 6-7).
The Circle and Rectangle classes were defined in Section 13.2, Abstract Classes. They
are all subclasses of GeometricObject . They are added to the set (lines 8-11).
Two circles of the same radius are added to the tree set (lines 9-10), but only one is stored,
because the two circles are equal and the set does not allow duplicates.
21.1 How do you create an instance of Set ? How do you insert a new element in a set?
How do you remove an element from a set? How do you find the size of a set?
21.2 If two objects o1 and o2 are equal, what is o1.equals(o2) and o1.hashCode()
== o2.hashCode() ?
21.3 What are the differences between HashSet , LinkedHashSet , and TreeSet ?
21.4 How do you traverse the elements in a set?
21.5 How do you sort the elements in a set using the compareTo method in the
Comparable interface? How do you sort the elements in a set using the Comparator
interface? What would happen if you added an element that could not be compared
with the existing elements in a tree set?
21.6 Suppose that set1 is a set that contains the strings red , yellow , and green , and
that set2 is another set that contains the strings red , yellow , and blue . Answer the
following questions:
Check
Point
What are in set1 and set2 after executing set1.addAll(set2) ?
What are in set1 and set2 after executing set1.add(set2) ?
What are in set1 and set2 after executing set1.removeAll(set2) ?
What are in set1 and set2 after executing set1.remove(set2) ?
What are in set1 and set2 after executing set1.retainAll(set2) ?
What is in set1 after executing set1.clear() ?
 
Search WWH ::




Custom Search