Professional Documents
Culture Documents
Chapter 9 Collections
Chapter 9 Collections
El Dick 1
2 Generics
COLLECTIONS
M. El Dick
Concrete type
M. El Dick M. El Dick
Defining Generic Classes Using Generic Classes
5 6
M. El Dick M. El Dick
More readability
More reliability
M. El Dick M. El Dick
Bounded Type Raw Type
9 10
Generic type as a subtype of another type For backward compatibility with earlier versions
of java
Unsafe (avoid whenever possible)
M. El Dick M. El Dick
Compile
Now, it is legal to invoke:
error max(new GenericStack<Integer>())
max(new GenericStack<Double>())
M. El Dick M. El Dick
Wildcard Generic Type Exercise 1
13 14
M. El Dick M. El Dick
M. El Dick 16 M. El Dick
public static<E extends Comparable<E>> E
max(E[][] list) {
E max = list[0][0];
return max;
}
17 M. El Dick M. El Dick
Natural order:
interface Comparable<T> { Ifthe objects are instances of Comparable use
public int compareTo(T o); compareTo()
}
String, Date, Calendar
All primitive types
M. El Dick M. El Dick
The Comparable Interface Example: Using Comparable
21 22
M. El Dick M. El Dick
import java.util.*
M. El Dick
Data Structure or “Container” Types of Containers
30
M. El Dick
Collection
32
31 Collection
Storing a collection of elements
M. El Dick M. El Dick
Types of Collection Interfaces and Implementations
33
Set
Interfaces Implementations
Stores non-duplicate elements
HashSet, LinkedHashSet,
List Set
... ...
TreeSet, ...
Stores an ordered collection of elements ArrayList,
List LinkedList, ... ...
Queue ...
M. El Dick
35
36 Set
M. El Dick M. El Dick
Set HashSet
37 38
Examples:
hashCode() in Integer returns its int value
hashCode() in Character returns Unicode of the character
hashCode() in String returns for(String x: set)
System.out.println(x);
s0 * 31 (n-1) + s1 * 30 (n-2) … + sn-1
where si is s.charAt(i)
M. El Dick
No ordering M. El Dick
No duplicates
41 42
M. El Dick M. El Dick
LinkedHashSet TreeSet
43 44
Ordering based on
natural order
Ordering based on
order of insertion
Using compareTo() of
Comparable of Class
String String
M. El Dick M. El Dick
TreeSet and Comparator
45 46
M. El Dick
Problem:
Read the words from a text file
48 List
The text file is entered by the user
Display all the non-duplicate words in alphabetical
order (natural order of Strings)
Display all the non-duplicate words in descending
order of length (a new order for Strings)
M. El Dick M. El Dick
List ListIterator
49 50
M. El Dick M. El Dick
ArrayList ArrayList
51 52
initialCapacity is optional
ArrayList<Integer> array =
new ArratList<Integer>(10);
int index = 0;
array.add(index, 7);
M. El Dick
LinkedList LinkedList
53 54
M. El Dick
55 56
M. El Dick M. El Dick
Exercise 1: Marathon
57
Classes: 58
Marathon
Static Methods for Lists and ArrayLists
List of runners who registered
List of runners who arrived
The Collections Class
Methods: getWinner(), registerNew(),
checkRegistered(), registerArrived(), registerDrop(),
registerDisqual(), displayRanking(), display...()
Runner:
Name, Number
Status: Running, Arrived, Dropped-out, Disqualified
Method: changeStatus() with conditions
M. El Dick M. El Dick
public Name(String firstName, String lastName) {
if (firstName == null || lastName == null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
M. El Dick M. El Dick
public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name) o;
Example (cont’d)
62
return n.firstName.equals(firstName) && n.lastName.equals(lastName);
}
class NameSort {
public static void main(String[] args) {
public int hashCode() { Name nameArray[] = {
return 31*firstName.hashCode() + lastName.hashCode(); new Name("John", "Smith"),
} new Name("Karl", "Ng"),
new Name("Jeff", "Smith"),
public String toString() { new Name("Tom", "Rich")
return firstName + " " + lastName;
};
}
List<Name> names = Arrays.asList(nameArray);
public int compareTo(Name n) {
Collections.sort(names);
int lastCmp = lastName.compareTo(n.lastName);
System.out.println(names);
return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
} }
61 } M. El Dick } M. El Dick
M. El Dick M. El Dick
Example: Binary Search Example: Shuffling and Copying
65 66
M. El Dick M. El Dick
Map
68
67
Map
Storing key-value pairs
M. El Dick M. El Dick
Map.Entry
69 70
M. El Dick M. El Dick
Map<String, Person> map = new HashMap<String, Person>();
// ...
map.put(key, val); // insert a key‐value pair
// ...
Set<String> keys = map.keySet(); // get the set of keys
HashMap<String, Person> id2Person; // iterate through the set of keys
…
Iterator<String> iter = keys.iterator();
Person p = id2Person.get("021212121");
if(p != null) { while (iter.hasNext()) {
System.out.println("found: " + p); String key = (String) iter.next();
} // ...
}
M. El Dick
HashMap, TreeMap, LinkedHashMap
73 74
HashMap
No ordering
LinkedHashMap
Ordering based on insertion order
TreeMap
Ordering based on natural order of keys
M. El Dick M. El Dick
Problem:
Count the number of occurrences of words in a text
Display the words and their occurrences in
alphabetical order
M. El Dick M. El Dick
Example: Without Generics
78
if(array.contains("Koko")) {
System.out.println("We have Koko");
}
String first = (String)array.get(0);
System.out.println("First: " + first);
M. El Dick M. El Dick
if(argsList.contains("Koko")) {
System.out.println("We have Koko");
}
String first = argsList.get(0); // no casting!
System.out.println("First: " + first);
M. El Dick