Java Collection Framework

antlertextureSoftware and s/w Development

Jul 14, 2012 (4 years and 11 months ago)

464 views

1
Java Collection Framework
2
Framework
 Interfaces (ADT, Abstract Data Types)
 Implementations (of ADT)
 Algorithms (sort)
 java.util.*
 Java 5 released!
 Lots of changes about collections
2
3
Interfaces
Collection
Set
List
Map
SortedSet
SortedMap
4
Implementations
Collection
Set
List
Map
SortedSet
SortedMap
TreeSet
TreeMap
ArrayList
LinkedList
HashMap
Linked
HashMap
Linked
HashSet
HashSet
3
5
Internals
LinkedList
Linked list
LinkedHashMapTreeMapHashMap
Map
ArrayList
List
LinkedHashSet TreeSetHashSet
Set
Hash table
Linked list
Balanced
tree
Resizable
array
Hash
table
interface
data structure
classes
6
Collection
 Collection of elements (references to
objects)
 It is un-specified whether they are
 Ordered / not ordered
 Duplicated / not duplicated
 Common constructors
 T()
 T(Collection c)
4
7
Collection interface
 int size()
 boolean isEmpty()
 boolean contains(Object element)
 boolean containsAll(Collection c)
 boolean add(Object element)
 boolean addAll(Collection c)
 boolean remove(Object element)
 boolean removeAll(Collection c)
 void clear()
 Object[] toArray()
 Iterator iterator()
8
Iterator
 Abstract means to iterate through all
collection elements
 Keeps track of the last visited element
of the related collection
 Interface method
 boolean hasNext()
 Object next()
 void remove()
5
9
Examples
Collection c = …;
for( Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();

}
Collection c = …;
for( Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();

}
Collection c = …;
Iterator i = c.iterator();
while( i.hasNext() ) {
Object o = i.next();

}
Collection c = …;
Iterator i = c.iterator();
while( i.hasNext() ) {
Object o = i.next();

}
10
Set
 Contains no methods other than those
inherited from Collection
 add()adds the restriction that no
duplicate elements are allowed
 e1.equals(e2) == false ∀ e1,e2 ∈ Σ
 Iterator
 The elements are traversed in no
particular order
6
11
SortedSet
 No duplicate elements
 Iterator
 The elements are traversed according to the
natural ordering (ascending)
 Augments Set interface
 Object first()
 Object last()
 SortedSet headSet(Object toElement)
 SortedSet tailSet(Object fromElement)
 SortedSet subSet(Object from, Object to)
12
Set implementations
 HashSet implements Set
 Hash tables as internal data structure
(faster)
 TreeSet implements SortedSet
 R-B trees as internal data structure
(computationally expensive)
 LinkedHashSet extends HashSet
 Elements are traversed by iterator
according to the insertion order
7
13
List
 Can contain duplicate elements
 Insertion order is preserved
 User can define insertion point
 Elements can be accessed by position
 Augments Collection interface
14
List additional methods
 void add(int index, Object element)
 boolean addAll(int index, Collection c)
 Object remove(int index)
 Object get(int index)
 Object set(int index, Object element)
 int indexOf(Object o)
 int lastIndexOf(Object o)
 List subList(int fromIndex, int toIndex)
8
15
List implementations
 ArrayList
 ArrayList()
 ArrayList(int initialCapacity)
 ArrayList(Collection c)
 void ensureCapacity(int minCapacity)
 LinkedList
 void addFirst(Object o)
 void addLast(Object o)
 Object getFirst()
 Object getLast()
 Object removeFirst()
 Object removeLast()
16
List implementations
ArrayList
 get(n)
 Constant time
 Insert (beginning)
and delete while
iterating
 Linear
LinkedList
 get(n)
 Linear time
 Insert (beginning)
and delete while
iterating
 Constant
9
17
From array …
Car[] garage = new Car[20];
garage[0] = new Car();
garage[1] = new ElectricCar();
garage[2] = new ElectricCar();
garage[3] = new Car();
for(int i=0; i<garage.length; i++){
garage[i].turnOn();
}
18
…to List
List garage = new ArrayList();
garage.add( new Car() );
garage.add( new ElectricCar() );
garage.add( new ElectricCar() );
garage.add( new Car());
Iterator i = garage.iterator();
Car c;
while ( i.hasNext() ) {
c = (Car) i.next();
c.turnOn();
}
10
19
Using ArrayList
ArrayList l = new ArrayList(2); // 2 refs to null
l.add(new Integer(11)); // 11 in position 0
l.add(0, new Integer(13)); // 11 in position 1
l.set(0, new Integer(20)); // 13 get replaced by 20
l.get(1); // returns 11
l.add(9, new Integer(30)); // NO: out of bounds
l.add(new Integer(30)); // OK, size extended
Iterator i = l.iterator();
while (i.hasNext()) {
...
}
20
Using LinkedList
LinkedList ll = new LinkedList();
ll.add(new Integer(10));
ll.add(new Integer(11));
ll.addLast(new Integer(13));
ll.addFirst(new Integer(20)); //20, 10, 11, 13
Iterator il = ll.iterator();
while (il.hasNext()) {
...
}
11
21
Map
 Map
 (key, value) binding
 No duplicate keys
 Examples
 identity code (String), person (Person)
 student ID (Integer), student (Student)
22
Map interface
 Object put(Object key, Object value)
 Object get(Object key)
 Object remove(Object key)
 boolean containsKey(Object key)
 boolean containsValue(Object value)
 public Set keySet()
 public Collection values()
 int size()
 boolean isEmpty()
 void clear()
12
23
SortedMap
 The elements are traversed according
to the keys’ natural ordering
(ascending)
 Augments Map interface
 SortedMap subMap(Object fromKey, Object toKey)
 SortedMap headMap(Object toKey)
 SortedMap tailMap(Object fromKey)
 Object firstKey()
 Object lastKey()
24
Implementations
 Analogous of Set
 Key order
 HashMap implements Map
 TreeMap implements SortedMap
 LinkedHashMap extends HashMap
13
25
HashMap
 Get/set takes constant time (in case of
no collisions)
 Automatic re-allocation when load
factor reached
 Constructor optional arguments
 load factor (default = .75)
 initial capacity (default = 16)
26
Using HashMap
Map students = new HashMap();
students.put(“123”,new Student(“123”,“Joe Smith”));
Studente s = (Student) students.get(“123”);
Iterator i = students.values().iterator();
while (i.hasNext()){
// i.next();
}
14
27
Note on iterators (1)
 It is unsafe to iterate over a collection you
are modifying at the same time
 Unless you are using the iterator methods, e.g.
Iterator:remove() and ListIterator:add()
List l = new LinkedList();
l.add(new Integer(10));
l.add(new Integer(11));
l.add(new Integer(13));
l.add(new Integer(20)); // 10,11,13,20
int count = 0;
for (Iterator i = l.iterator(); i.hasNext(); count++) {
i.next();
if (count==2) l.remove(count); // wrong
}
28
Note on iterators (1)
List l = new LinkedList();
l.add(new Integer(10));
l.add(new Integer(11));
l.add(new Integer(13));
l.add(new Integer(20)); // 10,11,13,20
int count = 0;
for (Iterator i = l.iterator();
i.hasNext();
count++)
{
i.next();
if (count==2) i.remove()); // ok
}
15
29
Note on iterators (2)
 It is unsafe to iterate over a collection you
are modifying at the same time
 Unless you are using the iterator methods, e.g.
Iterator:remove() and ListIterator:add()
List l = new LinkedList();
l.add(new Integer(10));
l.add(new Integer(11));
l.add(new Integer(13));
l.add(new Integer(20)); // 10,11,13,20
int count = 0;
for (Iterator i = l.iterator(); i.hasNext(); count++) {
i.next();
if (count==2) l.add(count, new Integer(22)); // wrong
}
30
Note on iterators (2)
List l = new LinkedList();
l.add(new Integer(10));
l.add(new Integer(11));
l.add(new Integer(13));
l.add(new Integer(20)); // 10,11,13,20
int count = 0;
for (ListIterator i = l.listIterator();
i.hasNext();
count++)
{
i.next();
if (count==2)
i.add(new Integer(22)); // ok
}
16
31
Object ordering
 Sorts the list according to the “natural
order”
 java.lang.String objects are lexicographically
ordered
 java.util.Date objects are chronologically ordered
 TRICK: both String and Date implement the
java.lang.Comparable interface
List list;

Collections.sort(list);
List list;

Collections.sort(list);
32
Object ordering
 Compares the receiving object with the
specified object, and returns a negative
integer, zero, or a positive integer as the
receiving object is less than, equal to, or
greater than the specified Object
 Implemented by String, Integer, Double,
Date, etc.
public interface Comparable {
public int compareTo(Object o);
}
public interface Comparable {
public int compareTo(Object o);
}
17
33
Object ordering
 How to sort a list of Student objects
according to the “natural order” by
means of the sort() method?
public class Student implements Comparable{
private String firstName;
private String lastName;
public int compareTo(Object o){
if (!(o instanceof Student)) System.exit(-1);
Student s = (Student)o;
int lastCmp = lastName.compareTo(s.lastName);
if(lastCmp!=0) return lastCmp
else return firstName.compareTo(s.firstName));
}
public class Student implements Comparable{
private String firstName;
private String lastName;
public int compareTo(Object o){
if (!(o instanceof Student)) System.exit(-1);
Student s = (Student)o;
int lastCmp = lastName.compareTo(s.lastName);
if(lastCmp!=0) return lastCmp
else return firstName.compareTo(s.firstName));
}
34
Object ordering (2)
 java.util
 Compares its two arguments,
returning a negative integer, zero, or a
positive integer as the first argument
is less than, equal to, or greater than
the second
public interface Comparator {
public int compare(Object o1, Object o2);
}
public interface Comparator {
public int compare(Object o1, Object o2);
}
18
35
Object ordering (2)
List students = new LinkedList();
students.add(new Student(“Mary”, “Smith”));
students.add(new Student(“Alice”, “Knight”));
students.add(new Student(“Joe”, “Smith”));
Collections.sort(students, new StudentComparator());
class StudentComparator implements Comparator {
public int compare(Object o1,Object o2){
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int lastCmp = s1.lastName.compareTo(s2.lastName);
if(lastCmp!=0) return lastCmp
else return s1.firstName.compareTo(s2.firstName));
}
class StudentComparator implements Comparator {
public int compare(Object o1,Object o2){
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int lastCmp = s1.lastName.compareTo(s2.lastName);
if(lastCmp!=0) return lastCmp
else return s1.firstName.compareTo(s2.firstName));
}
36
Object ordering - Note
 TreeSet()
 Natural ordering (elements must be
implementations of Comparable)
 TreeSet(Comparator c)
 Ordering is according to the comparator
rules, instead of natural ordering
 Same for TreeMap
19
37
Algorithms
 Static methods of java.util.Arrays class
 Work on object arrays
 sort(), binarySearch()
 Static methods of java.util.Collections class
 Work on lists
 sort() - merge sort, n log(n)
 binarySearch() – requires ordered sequence
 shuffle() – unsort
 reverse() - requires ordered sequence
 rotate() – of given a distance
 min(), max() – in a Collection
38
Arrays - example
 int binarySearch(Object[] a, Object key)
 Searches the specified object
 Array must be sorted into ascending
order according to natural ordering
 int binarySearch(Object[] a, Object key, Comparator c)
 Searches the specified object
 Array must be sorted into ascending
order according to the specified
comparator
20
39
Collections - example
 int binarySearch(List l, Object key)
 Searches the specified object
 List must be sorted into ascending order
according to natural ordering
 int binarySearch(List l, Object key, Comparator c)
 Searches the specified object
 List must be sorted into ascending order
according to the specified comparator