Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

M.

El Dick 1

2 Generics

COLLECTIONS
M. El Dick

Generics Defining Generic Interfaces


3 4

 Since JDK 1.5 Generic


type
 Define generic classes, interfaces, and methods

Concrete type

Runtime Error ! Compile Error !

M. El Dick M. El Dick
Defining Generic Classes Using Generic Classes
5 6

A generic class can have more than 1 parameter


E.g. <E1, E2, E3>

M. El Dick M. El Dick

Defining Generic Methods Advantages


7 8

 More readability
 More reliability

 Errors are detected at compile time instead of


runtime

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

Wildcard Generic Type Wildcard Generic Type


11 12

 Why do we need them?  How to use them?

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

 Revise GenericStack class to use an array rather


than an ArrayList
 Check the array size before adding to stack
 If the array is full, create a new array that doubles the
current array size and copy the elements from the
current array to the new array

Represents any object /


equivalent to:

M. El Dick M. El Dick

Exercise 2 public static<E extends Comparable<E>> E max(E[] 


list) {
15
E max = list[0];
 Write a generic method that returns the
for (int i = 1; i < list.length; i++) {
maximum in an array if (max.compareTo(list[i]) < 0) {
max = list[i];
}
 Write a generic method that returns the }
maximum in a 2-dimensional array
return max;
}

M. El Dick 16 M. El Dick
public static<E extends Comparable<E>> E 
max(E[][] list) {
E max = list[0][0];

for (int i = 1; i < list.length; i++) {


18 Ordering and Comparison
for (int j = 1; j < list[i].length; j++) {
if (max.compareTo(list[i][j]) < 0) {
max = list[i][j];
}
}
}

return max;
}

17 M. El Dick M. El Dick

Two Interfaces Two Approaches


19 20

 Natural order:
interface Comparable<T> {  Ifthe objects are instances of Comparable use
public int compareTo(T o); compareTo()
}
 String, Date, Calendar
 All primitive types

interface Comparator<T> {  Order by comparator:


public int compare(T o1, T o2);
 Create
your own comparator by implementing
}
Comparator 

M. El Dick M. El Dick
The Comparable Interface Example: Using Comparable
21 22

public interface Comparable <T> { public class Max {


public int compareTo(T o); public static Comparable max (Comparable o1, 
} Comparable o2){
if (o1.compareTo(o2) > 0)
return o1;
public class String extends Object  else
implements Comparable <String> { return o2;
public int compareTo(String o){…} } 
}
public class Date extends Object  }
implements Comparable <Date> {

public int compareTo(Date o){…} String s1 = « abcdee »; Date d1 = new Date();
… String s2 = « abcdef »; Date d2 = new Date();
} String s3 = (String) Date d3 = (Date)
Max.max(s1, s2);  Max.max(d1, d2); 
M. El Dick M. El Dick

Example: Using Both


@Override
public int compareTo(<Person> arg0) {
23 24 if (this.name.compareTo(arg0.name) < 0)
return ‐1;
public class Person implements Comparable<Person>{
if (this.name.compareTo(arg0.name) > 0)
public String name;
return 1;
public String lastName; if(this.name.compareTo(arg0.name) == 0){
public int age; if (this.lastName.compareTo(arg0.lastName) < 0)
return ‐1;
public Person(String n, String l, int a){ if (this.lastName.compareTo(arg0.lastName) > 0)

this.name = n; return 1;


if(this.lastName.compareTo(arg0.lastName) == 0)
this.lastName = l;
return 0;
this.age = a;
}
} return 0;
}
M. El Dick M. El Dick
}
import java.util.Comparator; public class Test  {

25 public class AgeComparator implements 26 public static void main(String[] args){


Comparator<Person> { Person p1 = new Person ("Rita","Aoun",22);
Person p2 = new Person("Elie","Kadoury",22);
@Override System.out.println(p1.compareTo(p2));
public int compare(Person arg0, Person arg1) {
if (arg0.age> arg1.age) AgeComparator c = new AgeComparator ();
return 1; System.out.println(c.compare(p1,p2));
if (arg0.age< arg1.age) }
return ‐1; }
return 0;
}
}

M. El Dick M. El Dick

The Collection Framework


27 Collections  Provides :
 Implementations of common high-level data
structures:
 Maps, sets, lists, etc.
 Classhierarchy with rules for adding new
implementations

 import java.util.*

M. El Dick
Data Structure or “Container” Types of Containers
30

 Object that stores other objects or “elements”  Collection:


 Poker hand (cards)  Storing a collection of elements
 Mail folder (letters)
 Telephone directory (names and phone numbers)  Map:
 Storing key-value pairs
 Used to organize and manipulate data

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 ...

 Stores objects processed as FIFO Queue ... ... ...

M. El Dick

35

36 Set

M. El Dick M. El Dick
Set HashSet
37 38

 Same methods and constants as Collection


 New condition
 No two elements e1 and e2 such that:
 e1.equals(e2) is true
 Default values:
 initialCapacityis 16
 loadFactor is 0.75 (between 0.0 and 1.0)
 How full the set is before it is allowed to increase its
capacity

When the size reaches 12 elements (16*0.75), the


M. El Dick capacity will be doubled toM.32
El Dick

HashSet and equals()


39 40

 Object elements should implement hashCode() of


class Object

 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

Circle and Rectangle


are subclasses of
GeometricObject

Only the first circle is added

M. El Dick

Exercise 1: Displaying non-duplicate


words
47

 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

 Allow duplicate elements  Bidirectional traversal of a list


 Access and store an element at a specific index

M. El Dick M. El Dick

ArrayList ArrayList
51 52

Dynamically growable array with efficient access by index

initialCapacity is optional

ArrayList<Integer> array = 
new ArratList<Integer>(10);
int index = 0;
array.add(index, 7);

When too many adds and removes, use LinkedList class!

M. El Dick
LinkedList LinkedList
53 54

Dynamically growable linked list with efficient insertions or removals

LinkedList<String> list = new LinkedList<String>();


list.add("hello 1");
list.addFirst("hello 0"); 
list.addLast("hello 2"); //equivalent to list.add()

When too many random accesses, use ArrayList class!

M. El Dick

55 56

Creating a list from an array

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

Class Collections Example: Sorting (1)


59 60

public class Name implements Comparable<Name> {


private final String firstName, lastName;

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

public class Seniority_order implements Comparator<Employee> {


Example: Sorting (2) public int compare(Employee e1, Employee e2) {
63 64 return e2.hireDate.compareTo(e1.hireDate);
}
 Given class Employee: }

public class Employee implements Comparable<Employee> { 


public Name name; . . .
public int number; public static void main(String[] args) {
public Date hireDate; List<Employee> e = new ArrayList<Employee>(...);
public int compareTo(Employee n) {
Seniority_order s = new Seniority_order();
return name.compareTo(n.name);
} Collections.sort(e, s);
 With natural ordering based on Name
...  System.out.println(e);
}  }

 List of employees in order of seniority?

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

HashMap Example: Iterating through a Map


71 72

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

Exercise 2: Occurrences of Words


75 76

 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

Collections and Generics-


ArrayList array = new ArrayList();
77
array.add("Koko");

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

Example: With generics


79

ArrayList<String> argsList = new ArrayList<String>();


argsList.add("Koko"); // argsList.add(7) would fail

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

You might also like