Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Collections Framework

Similar presentations


Presentation on theme: "Java Collections Framework"— Presentation transcript:

1 Java Collections Framework
Minseok Kwon 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? 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; }}}}} Do we have to implement these classes from scratch whenever we need them? Or does Java offer any classes to make this easy? 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
// Basic Operations size():int; isEmpty():boolean; contains(Object):boolean; add(Object):boolean; // Optional remove(Object):boolean; // Optional iterator():Iterator; // Bulk Operations containsAll(Collection):boolean; addAll(Collection):boolean; // Optional removeAll(Collection):boolean; // Optional retainAll(Collecton):boolean; // Optional clear():void; // Optional // Array Operations toArray():Object[]; toArray(Object[]):Object[]; Set List SortedSet Map SortedMap

7 Iterator hasNext():boolean; next():Object; remove():void; 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().

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 Races 1: A 2: Day 3: at 4: the 5: 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.
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: HashSet
import 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_1 1: [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. List // Positional Access get(int):Object; set(int,Object):Object; // Optional add(int, Object):void; // Optional remove(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;

21 Example: List Suppose the following elements are in the list:
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 ( )? What is the index of last 2? What is the index of 7? How can we change the list to ( )?

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. Index 6 4 7 9 2 ArrayList LinkedList 6 4 7 9 2 2

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()); 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); 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. John Book Sam Waterstone Rachael Green Sandra Balock key value 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.

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. Map // 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.Entry getKey():Object; getValue():Object; setValue(Object):Object;

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 How to create a Map object?
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? {Smith=30, Lewis=29, Anderson=31}
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 Example import 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();

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} 1 Exception ..... 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 Example import 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();

38 Another Example Map<Integer, String> universe;
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 ListIterator public 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"); 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 Result 1: [a, b, c, d] s = c 2: [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 % == 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) { 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); public static void findMin() { Hash_1 aHash_1 = new Hash_1( "A" + 0, "A" + 0); System.out.println("Find Min = " + 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/20000 Sun Sep 23 07:17:35 EDT 2007: 3000/20000 Sun Sep 23 07:17:37 EDT 2007: 6000/20000 Sun Sep 23 07:17:40 EDT 2007: 9000/20000 Sun Sep 23 07:17:45 EDT 2007: 12000/20000 Sun Sep 23 07:17:51 EDT 2007: 15000/20000 Sun Sep 23 07:17:58 EDT 2007: 18000/20000 Time for filling: 29133 Find Max = A20000 A20000 aHashMap: containsKey takes: 0 Find Middle = A10000 A10000 aHashMap: containsKey takes: 6 Find 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 d The 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 % java ComparableEx
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("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 2 import 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) { return (waitingListN - n.waitingListN);

51 Example 2 % java ComparableEx
public static void main(String args[]) { ComparableExWrong n[] = { new ComparableExWrong("You"), 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 Example import 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() { 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 ComparatorExC
sorted 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.


Download ppt "Java Collections Framework"

Similar presentations


Ads by Google