57
1 Java Collections Framework Minseok Kwon ([email protected] ) Department of Computer Science Rochester Institute of Technology

1 Java Collections Framework Minseok Kwon ([email protected])[email protected] Department of Computer Science Rochester Institute of Technology

Embed Size (px)

Citation preview

1

Java Collections Framework

Minseok Kwon ([email protected])

Department of Computer Science

Rochester Institute of Technology

2

What is a Collection?

• Suppose that you would like to store and sort given 10 numbers.• Where should we store these numbers? It should be easy to

access, insert, and remove.• Moreover, oftentimes we need data structures such as linked lists,

stacks, queues, heaps, and priority queues.

public class BubbleSort { public static void printIt(String data[] ) { for (int index=0; index<data.length; index++) System.out.println(index + "\t" + data[index] ); } public static void main( String args[] ) { String[] data = new String[3]; data[0] = "c"; data[1] = "b"; data[2] = "a"; sort(data); printIt(data); }

3

What is a Collection?

• Do we have to implement these classes from scratch whenever we need them?

• Or does Java offer any classes to make this easy?

public static void sort(String data[] ) { for (int index=0; index < data.length - 1; index++) { for (int walker=0; walker < data.length-1-index; walker++) { if ( data[walker].compareTo(data[walker+1]) > 0 ) { String tmp = data[walker]; data[walker] = data[walker + 1]; data1[walker+1] = tmp; }}}}}

import java.util.*;

public class Sort { public static void main(String args[]) { List l = Arrays.asList(args); Collections.sort(l); System.out.println(l); }}

4

Java Collections Framework

• Java provides these useful data structures, so that the user doesn’t have to reinvent the wheel.

• It is called the Java Collections Framework.• Advantages

– Improved productivity– Better run-time efficiency (optimized functions)– Increased program generality (standardized interfaces)– Interoperability (standardized interfaces)

• A collection is a container object that stores a group of objects, often referred to as elements.

• Examples: a mail folder, a telephone directory, etc.

5

Java Collections Framework

• The Java collections framework is made up of a set of interfaces and classes for working with groups of objects.

• Three components– Interfaces: Abstract data types defining behaviors– Implementations: Concrete implementations of the collection

interfaces. – Algorithms: Methods that perform useful computations, like

searching and sorting, on objects that implement collection interfaces.

• Three major types of collections: set, list, and map.

6

The Collection Interface

Collection

Set List

SortedSet

Map

SortedMap

// Basic Operationssize():int; isEmpty():boolean; contains(Object):boolean; add(Object):boolean; // Optional remove(Object):boolean; // Optionaliterator():Iterator;

// Bulk Operations containsAll(Collection):boolean; addAll(Collection):boolean; // OptionalremoveAll(Collection):boolean; // Optional retainAll(Collecton):boolean; // Optional clear():void; // Optional

// Array Operations toArray():Object[]; toArray(Object[]):Object[];

Collection

7

Iterator

• Allows us to move in order through a collection from one element to another.

• We can check if there is a next element by calling hasNext().

• Successive calls to the next() method return successive elements of the series.

• The remove() method removes from the underlying Collection the last element that was returned by next().

hasNext():boolean; next():Object; remove():void;

Iterator

8

Iterator

import java.util.*;

public class UseIter { public static void main(String args[]) { List l = Arrays.asList(args); Iterator iter = l.iterator(); while( iter.hasNext() ) { System.out.println(++index + “: “ + (String)iter.next()); } }}

% java UseIter A Day at the Races1: A2: Day3: at4: the5: Races

9

Simpler iterator in Java 1.5

• Old way for iterators

Iterator iter = new set.iterator();while (iter.hasNext()) System.out.println(iter.next() + “ “);

• Simpler way

for (String element: set) System.out.println(element + “ “);

10

Math Sets

• Suppose that we have the following sets A, B, and C.– A = {5, 14, 3}– B = {1, 3, 4, 5, 10, 14}– C = {1, 10, 20, 30}

• Can you find the answers?– 14 in A– 10 not in A– A U B– A intersection B– C subset B– A subset B– Is a set a collection of unique elements?

11

Math Sets

• What methods are used to insert an element to a set?• How do we check if that element is in a set?

• What methods are used for common set operations such as union, intersection, and difference?

• How do we know one set is a subset of another set?

• How large is the set?• Is the set empty?

• How do we visit each element in the set?

12

Set Bulk Operations

• Suppose that s1 and s2 are sets.

• s1.containsAll(s2) returns true if s2 is a subset of s1.

• s1.addAll(s2) transforms s1 into the union of s1 and s2.

• s1.retainAll(s2) transforms s1 into the intersection of s1 and s2.

13

Sets

• A collection of unique elements that are position independent.

• A set ensures no duplicate elements.• Two sets are equal if they contain exactly the same

elements, regardless of where those elements may appear.

• The Set interface extends Collection and contains no methods other than those inherited from Collection

• HashSet is a popular concrete class that implements Set.

• TreeSet is another concrete class that guarantees that the elements in the set are sorted.

14

HashSet and TreeSet

• HashSet is a concrete class that implements Set.• Objects are added to a hash set according to their hash

code.• What is a hash code?

– A hash code is an integer value that uniquely identifies an object.

• Hence, HashSet does not necessarily store the elements in the order they were inserted.

• TreeSet is a concrete class that implements the SortedSet interface that inherits Set.

• All the elements in TreeSet are sorted.

15

How to Use HashSet and TreeSet?

import java.util.*;public class TestHashSet { public static void main(String args[]) { Set<String> set = new HashSet<String>(); set.add(“London”); set.add(“Paris”); set.add(“New York”); System.out.println(set); Iterator iter = set.iterator(); while (iter.hasNext()) System.out.print(iter.next() + “ “); System.out.println();

TreeSet<String> treeSet = new TreeSet<String>(set); System.out.println(treeSet); for (Object elem: treeSet) System.out.print(elem.toString() + “ “); }}

% java TestHashSet[New York, Paris, London]New York Paris London [London, New York, Paris]London New York Paris

16

Another Example: HashSetimport java.util.HashSet;import java.util.Set;

public class HashSetEx_1 {

private Set<Integer> universe; private Set<Integer> fill(int soMany) { Set<Integer> universe = new HashSet<Integer>(); for ( int index = 0; index < soMany; index ++ ) universe.add(new Integer(index)); return universe; } public static void main(String args[]) { Set<Integer> universe; HashSetEx_1 aHashSetEx_1 = new HashSetEx_1(); universe = aHashSetEx_1.fill(3); System.out.println("1: " + universe );

universe.remove( new Integer(1) ); System.out.println("2: " + universe );

universe.remove( new Integer(10) ); System.out.println("3: " + universe ); }}

17

Result

% java HashSetEx_11: [0, 1, 2]2: [0, 2]3: [0, 2]

18

Problems: Set

• Create two hash sets:– {“George”, “Jim”, “John”, “Blake”, “Kevin”, “Michael”}– {“George”, “Katie”, “Kevin”, “Michelle”, “Ryan”}

• Find their union, difference, and intersection.

• Write a Java program that reads words in a file, remove duplicates, and prints only unique words in ascending order. The text file is passed as a command-line argument.

19

What Sets Cannot Do

• What if we want to store duplicate elements?

• We also want to store, remove and retrieve elements at specific locations.

• Use List!!!

20

Lists

• List extends Collection to define an ordered collection with duplicates allowed.

• In addition to the methods in Collection, List includes operations for positional access, search, list iteration, and range view.

// Positional Access get(int):Object; set(int,Object):Object; // Optionaladd(int, Object):void; // Optionalremove(int index):Object; // Optional addAll(int, Collection):boolean; // Optional // Search int indexOf(Object); int lastIndexOf(Object); // Iteration listIterator():ListIterator; listIterator(int):ListIterator; // Range-view List subList(int, int):List;

List

21

Example: List

• Suppose the following elements are in the list:– List: 6 4 7 9 2 0 2

• Questions:– How to retrieve the 5th element?– How to change the 4th element to 13?– How to insert 10 after the 2nd element?– How to delete the 3rd element?– How to obtain the sublist containing (9 2 0)?– What is the index of last 2?– What is the index of 7?– How can we change the list to (6 4 7 9 2 11 12 13 0 2)?

22

ArrayList and LinkedList

• ArrayList and LinkedList are two concrete implementation of List.

• ArrayList stores elements in an array.• LinkedList stores elements in a linked list.

6 4 7 9 2 0 2ArrayList

0 1 2 3 4 5 6 Index

6 4 7 9 2 0 2LinkedList

23

ArrayList and LinkedList

• Which one should we use?• ArrayList is good for random access while LinkedList

provides more efficient insertion and deletion.• Why?

• ArrayList grows its capacity as more elements are added.• LinkedList has additional utility methods.

+ LinkedList()+ LinkedList(c: Collection)+ addFirst(o: Object): void+ addLast(o: Object): void+ getFirst(): Object+ getLast(): Object+ removeFirst(): Object+ removeLast(): Object

Java.util.LinkedList

24

Using ArrayList and LinkedList

import java.util.*;public class TestArrayAndLinkedList { public static void main(String args[]) { List<Integer> al = new ArrayList<Integer>(); al.add(1); al.add(2); al.add(3); al.add(4); al.add(5); System.out.println(al);

LinkedList<Object> ll = new LinkedList<Object>(al); ll.add(1, “red”); ll.removeLast(); ll.addFirst(“green”); ListIterator list = ll.listIterator(); while (list.hasNext()) System.out.print(list.next() + “ “); System.out.println(); list = ll.listIterator(ll.size()); while(list.hasPrevious()) System.out.print(list.previous() + “ “); }}

25

Result

% java TestArrayAndLinkedList[1, 2, 3, 4, 5]green 1 red 2 3 4 4 3 2 red 1 green

26

Static Methods for Lists and Collections

• Is there a sorted list like TreeSet in a set?• No. Then how can we sort a list?• Use Collections!

List<String> list = Arrays.asList(“red”, “green”, “blue”);Collections.sort(list);System.out.println(list);Collections.sort(list, Collections.reverseOrder());System.out.println(list);List<Integer> list1 = Arrays.asList(2, 4, 7, 10, 11, 45, 50);System.out.println(Collections.binarySearch(list1,7);Collections.reverse(list1);System.out.println(list1);Collections.shuffle(list1);System.out.println(list1);Collections.copy(list1, list2);System.out.println(list2);System.out.println(Collections.max(list));System.out.println(Collections.min(list));

27

Problem: Lists

• Write a program that lets the user enter numbers, and display them in descending order.

• Write a Java program that implements a priority queue using a list. This queue holds strings and bases the priority on the alphabetical order of the strings. Strings at the beginning of the dictionary have priority over those at the end.– public void enqueue(String val);– public String dequeue();– public boolean isEmpty();

28

What is a Map?

• A Map is a collection of keys that map to corresponding values.

123-45-6789123-45-7867123-22-9184156-26-2234

John BookSam WaterstoneRachael GreenSandra Balock

• We probably want the following operations: – Add a new (key, value) pair.– Update an existing (key, value) pair.– Remove an existing (key, value) pair. – Query if a given key is in the map.– Obtain a set of keys.– Obtain a set of values.

key value

29

What is a Map?

• Write a program that reads a text file and displays the words in descending order of occurrence counts.

• For example, in the text “In the name of the father, and of the son and of the holy spirit”, count the occurrences of words.

• What are the results?

• What are keys and values?

30

Maps

• The Map interface maps keys to the elements.• The keys are like indexing objects (the indexes in List

are integers).• A map cannot contain duplicate keys, and each key

maps to only one value.

// Basic Operations put(Object, Object):Object; get(Object):Object; remove(Object):Object; containsKey(Object):boolean; containsValue(Object):boolean; size():int; isEmpty():boolean; // Bulk Operations void putAll(Map t):void; void clear():void; // Collection Views keySet():Set; values():Collection; entrySet():Set;

Map

getKey():Object; getValue():Object; setValue(Object):Object;

Map.Entry

31

Example: Map

• Suppose the following map of student names and their 707 exam scores. – Map: {“Keith”=45, “Ryan”=100, “Susan”=90, “Jack”=80}

• Legitimate questions– How to retrieve Keith’s score?– How to check if there is Susan in my 707 course?– How to insert a new student with his/her score?– How to delete Jack’s score?– How to check if there is a student with the score 80?– How to get the complete list of students? – How can we compute the average score?

32

Java Maps

• Java provides three Map classes– HashMap is efficient for locating a value, inserting a mapping

and deleting a mapping, but order of elements does not matter.– LinkedHashMap extends HashMap and maintains

insertion/access order.– TreeMap is efficient for traversing the keys in a sorted order.

• How to create a Map object?

HashMap<String, Integer> myMap = new HashMap<String, Integer>();

• No iterator is provided in Map.• Then how can we traverse a map?

33

Java Maps

• The entrySet() method in Map returns an entry set of the mappings -- Map.Entry<KT, VT>.

Set<Map.Entry<String, Integer>> myEntrySet = myMap.entrySet();myEntrySet.xx.getKey();myEntrySet.xx.getValue();

• The toString() method prints out an entry in “key=value” format.

System.out.println(hashMap);

{Cook=29, Smith=30, Lewis=29, Anderson=31}

34

How to Use Map?import java.util.*;public class TestMap { public static void main(String[] args) { Map<String, Integer> hashMap = new HashMap<String, Integer>(); hashMap.put(“Smith”, 30); hashMap.put(“Anderson”, 31); hashMap.put(“Lewis”, 29); System.out.println(hashMap);

Map<String, Integer> treeMap = new TreeMap<String, Integer>(hashMap); System.out.println(treeMap);

Map<String, Integer> linkedHashMap = new LinkedHashMap<String, Integer>(16, 0.75f, true); linkedHashMap.put(“Smith”, 30); linkedHashMap.put(“Anderson”, 31); linkedHashMap.put(“Lewis”, 29); linkedHashMap.put(“Cook”, 29); System.out.println(linkedHashMap); }}

{Smith=30, Lewis=29, Anderson=31}{Anderson=31, Lewis=29, Smith=30}{Smith=30, Anderson=31, Lewis=29, Cook=29}

35

Another Exampleimport java.util.HashMap;import java.util.Map;

public class HashMapEx { private Map<Integer, String> universe; private Map<Integer, String> fill(int soMany) { universe = new HashMap<Integer, String>(); for ( int index = 0; index < soMany; index ++ ) universe.put(new Integer(index), "_" + index); return universe; }

private Map<Integer, String> delete(int what) { try { for (Integer id : universe.keySet() ) { System.out.println(id); if ( id.equals(new Integer(what) ) ) universe.remove(id); } } catch ( Exception e ) { System.out.println("Exception ..... "); e.printStackTrace(); } return universe; }

36

Another Example public static void main(String args[]) { Map<Integer, String> universe; HashMapEx aHashMapEx = new HashMapEx(); universe = aHashMapEx.fill(3); System.out.println("1: " + universe ); aHashMapEx.delete(1); System.out.println("2: " + universe );

}}

1: {0=_0, 1=_1, 2=_2}01Exception ..... java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793) at java.util.HashMap$KeyIterator.next(HashMap.java:828) at HashMapEx.delete(HashMapEx.java:18) at HashMapEx.main(HashMapEx.java:39)2: {0=_0, 2=_2}

37

Another Exampleimport java.util.*;public class HashMapEx_2 {

private Map<Integer, String> universe; private Map<Integer, String> fill(int soMany) { universe = new HashMap<Integer, String>(); for ( int index = 0; index < soMany; index ++ ) universe.put(new Integer(index), "_" + index); return universe; }

private Map<Integer, String> delete(int what) { Set<Integer> keySet = universe.keySet(); Iterator<Integer> aIterator = keySet.iterator(); while ( aIterator.hasNext() ) { Integer aInt = aIterator.next(); if ( aInt.equals( new Integer(what) ) ) aIterator.remove(); } return universe; }

38

Another Example public static void main(String args[]) { Map<Integer, String> universe; HashMapEx_2 aHashMapEx_2 = new HashMapEx_2(); universe = aHashMapEx_2.fill(3); System.out.println("1: " + universe ); aHashMapEx_2.delete(1); System.out.println("2: " + universe );

}}

1: {0=_0, 1=_1, 2=_2}2. {0=_0, 2=_2}

39

Problem: Maps

• Write a Java program that represents a bookshelf. Books on the shelf are stored and retrieved by ISBN.– The addTitle(String isbn, String title) method adds a book to the

bookshelf.– The getTitle(String isbn) method returns the title associated with

the given ISBN.– The removeTitle(String isbn) method removes the title with the

specified title from the shelf.– The getAllTitles() method returns a list that contains all of the

titles on the shelf.

• Write a program that counts the number of appearance for each word in a file, and print them in ascending order alphabetically.

40

ListIteratorpublic class ListItereatorEx { private Stack<String> palindrom; private Collection<String> fill(String words[]) { palindrom = new Stack<String>(); for (String id : words ) { palindrom.push(id); } return palindrom; } private Collection<String> leftRight() { ListIterator<String> aListIterator = palindrom.listIterator(2); String s = aListIterator.next(); System.out.println("s = " + s ); aListIterator.set("ZZ top"); return palindrom; } public static void main(String args[]) { Collection<String> aStack; String theOnes[] = { "a", "b", "c", "d" }; ListItereatorEx o = new ListItereatorEx(); aStack = o.fill(theOnes ); System.out.println("1: " + aStack ); aStack = o.leftRight(); System.out.println("2: " + aStack ); }}

41

Result1: [a, b, c, d]s = c2: [a, b, ZZ top, d]

42

HashMap

• s1.equals(s2) implies that s1.hashCode() == s2.hashCode().import java.util.*;public class Hash_1 extends Name_1 { static final int MAX = 20000; static HashMap aHashMap = new HashMap(); public Hash_1(String firstName, String lastName) { super(firstName, lastName); } public static void init() { long milliSeconds = System.currentTimeMillis(); for ( int index = 0; index <= MAX; index ++ ) { if ( index % 3000 == 0 ) System.out.println(new Date()+”: ” index + "/" + MAX ); aHashMap.put( new Hash_1( "A" + index, "A" + index), new Hash_1( "A" + index, "A" + index) ); } System.out.println("Time for filling: " + ( System.currentTimeMillis() - milliSeconds) ); } public static void findIt(Hash_1 aHash_1) { long milliSeconds = System.currentTimeMillis(); if ( aHashMap.containsKey( aHash_1 ) ) System.out.print("\taHashMap: containsKey takes: "); System.out.println(System.currentTimeMillis() - milliSeconds); }

43

HashMap public static void findMax() { Hash_1 aHash_1 = new Hash_1( "A" + MAX, "A" + MAX); System.out.println("Find Max = " + aHash_1); findIt(aHash_1); } public static void findMiddle() { Hash_1 aHash_1 = new Hash_1( "A" + ( MAX/2), "A" + ( MAX/2)); System.out.println("Find Middle = " + aHash_1); findIt(aHash_1); } public static void findMin() { Hash_1 aHash_1 = new Hash_1( "A" + 0, "A" + 0); System.out.println("Find Min = " + aHash_1); findIt(aHash_1); } public static void main(String args[] ) { long milliSeconds = System.currentTimeMillis();

init(); findMax(); findMiddle(); findMin(); System.exit(0); }}

44

Result

Sun Sep 23 07:17:35 EDT 2007: 0/20000Sun Sep 23 07:17:35 EDT 2007: 3000/20000Sun Sep 23 07:17:37 EDT 2007: 6000/20000Sun Sep 23 07:17:40 EDT 2007: 9000/20000Sun Sep 23 07:17:45 EDT 2007: 12000/20000Sun Sep 23 07:17:51 EDT 2007: 15000/20000Sun Sep 23 07:17:58 EDT 2007: 18000/20000Time for filling: 29133Find Max = A20000 A20000 aHashMap: containsKey takes: 0Find Middle = A10000 A10000 aHashMap: containsKey takes: 6Find Min = A0 A0 aHashMap: containsKey takes: 3

45

Sorting Maps

import java.util.*;public class UseCollectionS { static ArrayList aArrayList = new ArrayList(); static HashMap aHashMap = new HashMap();

public static void main(String args[] ) { for ( int index = 0; index < args.length; ++index) aHashMap.put(args[index], args[index] + " " + new Date() ); System.out.println("The HashMap: " + aHashMap); List l = new ArrayList(aHashMap.values()); Collections.sort(l); System.out.println("The List: " + l); }}

% java UseCollectionS a b c dThe HashMap: {d=d Tue Mar 19 15:24:46 EST 2002, c=c Tue Mar 19 15:24:46 EST 2002, b=b Tue Mar 19 15:24:46 EST 2002, a=a Tue Mar 19 15:24:46 EST 2002}The List: [a Tue Mar 19 15:24:46 EST 2002, b Tue Mar 19 15:24:46 EST 2002, c Tue Mar 19 15:24:46 EST 2002, d Tue Mar 19 15:24:46 EST 2002]

46

Comparable

• How does a collection know how to sort its objects?• Use Comparable

– compareTo() is used to determine an ordering.• a < b means a.compareTo(b) < 0

• a == b means a.compareTo(b) == 0

• a > b means a.compareTo(b) > 0

– Recommended: (x.compareTo(y) == 0 ) == (x.equals(y))– Lists and arrays of objects that implement Comparable can be

sorted using:• Collections.sort() or Arrays.sort()

public interface Comparable { public int compareTo(Object o);}

47

Comparable

import java.util.*;public class Name implements Comparable { String first; String last; public Name( String firstName, String lastName ) { first = firstName; last = lastName; } public String getLast() { return last; } public String getFirst() { return first; } public int compareTo( Object o ) { Name anotherName = (Name)o; int retVal = last.compareTo( anotherName.getLast() ); if (retVal == 0) { retVal = first.compareTo( anotherName.getFirst() ); } return retVal; }}

48

Example 1

import java.util.*;public class ComparableEx implements Comparable { protected static int soManyS; protected String name; protected int waitingListN; public ComparableEx(String name) { if (name==null) throw new NullPointerException(); this.name = name; this.waitingListN = soManyS ++; } public String getName() { return name; } public boolean equals(Object o) { if (!(o instanceof ComparableEx)) return false; ComparableEx n = (ComparableEx)o; return name.equals(n.name); } public String toString() { return name + " - " + waitingListN; }

49

Example 1 public int compareTo(Object o) { ComparableEx n = (ComparableEx)o; return (this.name.compareTo(n.name)); } public static void main(String args[]) { ComparableEx n[] = { new ComparableEx("You"), new ComparableEx("Bond"), new ComparableEx("Bond"), new ComparableEx("Jack"), new ComparableEx("Elwood") }; List l = Arrays.asList(n); Collections.sort(l); System.out.println(l); }}

% java ComparableEx[Bond - 1, Bond - 2, Elwood - 4, Jack - 3, You - 0]

50

Example 2import java.util.*;public class ComparableExWrong implements Comparable { protected static int soManyS; protected String name; protected int waitingListN; public ComparableExWrong(String name) { if (name==null) throw new NullPointerException(); this.name = name; this.waitingListN = soManyS ++; } public String getName() { return name; } public boolean equals(Object o) { if (!(o instanceof ComparableExWrong)) return false; ComparableExWrong n = (ComparableExWrong)o; return name.equals(n.name); } public String toString() { return name + " - " + waitingListN; } public int compareTo(Object o) { ComparableExWrong n = (ComparableExWrong)o; return (waitingListN - n.waitingListN); }

51

Example 2 public static void main(String args[]) { ComparableExWrong n[] = { new ComparableExWrong("You"), new ComparableExWrong("Bond"), new ComparableExWrong("Bond"), new ComparableExWrong("Jack"), new ComparableExWrong("Elwood") }; List l = Arrays.asList(n); Collections.sort(l); System.out.println(l); }}

% java ComparableEx[You - 0, Bond - 1, Bond - 2, Jack - 3, Elwood - 4]

52

Comparator

• What if you want to insert elements of different types into a tree set, and the elements may not be instances of java.lang.Comparable?

• In this case, we can define a comparator to compare these elements.

• A comparator is an object that encapsulates an ordering like iterator for an iteration.

• Two methods need to be defined– public int compare(Object element1, Object element2) returns a

negative value if element1 < element2, a positive value if element1 > element2, and zero if they are equal.

– public boolean equals(Object element) returns true if the specified object is also a comparator and imposes the same ordering as this comparator.

53

How to Define Comparator?

public class DogByBreedAndName implements Comparator { public int compare( Object o1, Object o2 ) { Dog d1 = (Dog)o1; Dog d2 = (Dog)o2;

int retVal = d1.getBreed().compareTo( d2.getBreed() ); if (retVal == 0) { retVal = d1.getName().compareTo( d2.getName() ); } return retVal; }}

public class TestDogWithComparator { public class static void main(String args[]) { Set<Dog> set = new TreeSet<Dog>(new DogByBreedAndName()); set.add(new Dog(“AA”, “chiwahah”)); set.add(new Dog(“BB”, “Shephard”)); set.add(new Dog(“CC”, “pitbull”)); set.add(new Dog(“DD”, “sheepdog”)); for (Dog elem: set) System.out.println(elem); }}

54

Correct Exampleimport java.util.*;public class ComparatorExC { static final Comparator theNth = new Comparator() { public int compare(Object o1, Object o2) { WaitingList n1 = (WaitingList)o1; WaitingList n2 = (WaitingList)o2; int intCompareV = n1.waitingListN - n2.waitingListN; return ( intCompareV == 0 ? n1.name.compareTo(n2.name ): intCompareV ); } }; static final Comparator nameC = new Comparator() { public int compare(Object o1, Object o2) { WaitingList n1 = (WaitingList)o1; WaitingList n2 = (WaitingList)o2; int nameCompareV = n1.name.compareTo(n2.name); return ( nameCompareV == 0 ? n1.waitingListN - n2.waitingListN: nameCompareV ); } }; protected static int soManyS; protected String name; protected int waitingListN;

55

Correct Example public ComparatorExC(String name) { if (name==null) throw new NullPointerException(); this.name = name; this.waitingListN = soManyS ++; } public ComparatorExC(String name, int waitingListN) { this(name); this.waitingListN = waitingListN; } public String getName() { return name; } public String toString() { return name + " - " + waitingListN; } public static void main(String args[]) { WaitingList n[] = { new WaitingList("Bond"), new WaitingList("Jack"), new WaitingList("Bond”, 2), new WaitingList("Elwood"), new WaitingList("You", -1), new WaitingList("Me", -1) }; List l = Arrays.asList(n); Collections.sort(l, nameC); System.out.println("sorted by name: " + l); Collections.sort(l, theNth); System.out.println("sorted by rank: " + l); }}

56

Result

% java ComparatorExCsorted by name: [Bond - 0, Bond - 2, Elwood - 3, Jack - 1, Me - -1, You - -1]sorted by rank: [Me - -1, You - -1, Bond - 0, Jack - 1, Bond, 2 - 2, Elwood - 3]

57

Problem: Comparator

• Write the GeometricObjectComparator class that extends Comparator and sorts the geometric objects by their area.

• In your main method, create different shapes (Rectangle, Circle, Triangle) and store them into a TreeSet.

• Test if those shapes are sorted by their area.