2-Java_CollectionFramework_10b
2-Java_CollectionFramework_10b
Framework
Collection Framework
A collection framework is a unified architecture for
representing and manipulating collections. It has:
– Interfaces: abstract data types representing
collections
– Implementations: concrete implementations of
the collection interfaces
– Algorithms: methods that perform useful
computations, such as searching and sorting
• These algorithms are said to be polymorphic:
the same method can be used on different
implementations
Collection interfaces
Queue
Collection Interface continued
• Set →
The familiar set abstraction.
No duplicates; May or may not be ordered.
• List →
Ordered collection, also known as a sequence.
Duplicates permitted; Allows positional access
• Map →
A mapping from keys to values.
Each key can map to at most one value (function).
The keys are like indexes. In List, the indexes are
integer. In Map, the keys can be any objects.
• Queue →
Ordered collection. FIFO (First In First Out)
Type Trees for Collections
Iterable<E> Iterator<E>
Collection<E> ListIerator<E>
LinkedHashSet<E>
Map<K,V>
EnumMap<K,V>
WeakHashMap<K,V>
SortedMap<K,V>
HashMap<E>
TreeMap<K,V>
LinkedHashMap<K,V>
6
Java Collection Framework hierarchy,
cont.
Set and List are subinterfaces of Collection.
SortedSet TreeSet
Collection AbstractCollection
Vector Stack
List AbstractList
ArrayList
AbstractSequentialList LinkedList
Deque
7
Collection Interface
• Defines fundamental methods
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element); // Optional
boolean remove(Object element); // Optional
Iterator iterator();
• These methods are enough to define the basic
behavior of a collection
• Provides an Iterator to step through the elements in
the Collection
8
Interface Collection
•add(o) Add a new element
• addAll(c) Add a collection
•clear() Remove all elements
•contains(o) Membership checking.
•containsAll(c) Inclusion checking
•isEmpty() Whether it is empty
•iterator() Return an iterator
•remove(o) Remove an element
•removeAll(c) Remove a collection
•retainAll(c) Keep the elements
•size() The number of elements
Iterator Interface
• Defines three fundamental methods
Object next()
boolean hasNext()
void remove()
• These three methods provide access to the
contents of the collection
• An Iterator knows position within collection
• Each call to next() “reads” an element from the
collection
Then you can use it or remove it
10
Iterator Position
11
Example - SimpleCollection
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
System.out.println(c.getClass().getName());
for (int i=1; i <= 10; i++) {
c.add(i + " * " + i + " = "+i*i);
}
Iterator iter = c.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}} 12
List Interface Context
Collection
List
13
List Interface
• The List interface adds the notion of
order to a collection
• The user of a list has control over where
an element is added in the collection
• Lists typically allow duplicate elements
• Provides a ListIterator to step through the
elements in the list.
14
ListIterator Interface
• Extends the Iterator interface
• Defines three fundamental methods
void add(Object o) - before current position
boolean hasPrevious()
Object previous()
• The addition of these three methods defines
the basic behavior of an ordered list
• A ListIterator knows position within list
15
Iterator Position - next(), previous()
16
ArrayList and LinkedList Context
Collection
List
ArrayList LinkedList
17
List Implementations
• ArrayList
low cost random access
high cost insert and delete
array that resizes if need be
• LinkedList
sequential access
low cost insert and delete
high cost random access
18
ArrayList overview
• Constant time positional access (it’s an array)
• One tuning parameter, the initial capacity
22
Set Interface Context
Collection
Set
23
Set Interface
• Same methods as Collection
different contract - no duplicate entries
• Defines two fundamental methods
boolean add(Object o) - reject duplicates
Iterator iterator()
• Provides an Iterator to step through the elements
in the Set
No guaranteed order in the basic Set interface
There is a SortedSet interface that extends Set
24
HashSet and TreeSet Context
Collection
Set
HashSet TreeSet
25
HashSet
• Find and add elements very quickly
uses hashing implementation in HashMap
• Hashing uses an array of linked lists
The hashCode() is used to index into the array
Then equals() is used to determine if element is in
the (short) list of elements at that index
• No order imposed on elements
• The hashCode() method and the equals() method
must be compatible
if two objects are equal, they must have the same
hashCode() value
26
TreeSet
• Elements can be inserted in any order
• The TreeSet stores them in order
• An iterator always presents them in order
• Default order is defined by natural order
objects implement the Comparable interface
TreeSet uses compareTo(Object o) to sort
27
Map Interface Context
Map
28
Map Interface
• Stores key/value pairs
• Maps from the key to the value
• Keys are unique
a single key only appears once in the
Map
a key can map to only one value
• Values do not have to be unique
29
Map methods
Object put(Object key, Object value)
Object get(Object key)
Object remove(Object key)
boolean containsKey(Object key)
boolean containsValue(Object value)
int size()
boolean isEmpty()
30
Map views
• A means of iterating over the keys and values in a Map
• Set keySet()
returns the Set of keys contained in the Map
• Collection values()
returns the Collection of values contained in the Map.
This Collection is not a Set, as multiple keys can map to
the same value.
• Set entrySet()
returns the Set of key-value pairs contained in the Map.
The Map interface provides a small nested interface
called Map.Entry that is the type of the elements in this
Set.
31
HashMap and TreeMap Context
Map
HashMap TreeMap
32
HashMap and TreeMap
• HashMap
The keys are a set - unique, unordered
Fast
• TreeMap
The keys are a set - unique, ordered
Same options for ordering as a TreeSet
– Natural order (Comparable, compareTo(Object))
– Special order (Comparator, compare(Object,
Object))
33
Bulk Operations
• In addition to the basic operations, a Collection may
provide “bulk” operations
35
Utilities
• The Collections class provides a number of
static methods for fundamental algorithms
• Most operate on Lists, some on all Collections
Sort, Search, Shuffle
Reverse, fill, copy
Min, max
• Wrappers
synchronized Collections, Lists, Sets, etc
unmodifiable Collections, Lists, Sets, etc
36
Concrete Collections
TreeSet
Set HashSet
(sortedSet)
ArrayList
List LinkedList
Vector
HashMap TreeMap
Map
Hashtable (sortedMap)
39
The Arrays Class
The Arrays class contains various static methods
➢ sorting arrays
➢searching arrays
➢comparing arrays
➢filling array elements
➢convert array to list.
40
The Arrays Class UML Diagram
Arrays
+asList(a: Object[]): List Returns a list from an array of objects
Overloaded binarySearch method for byte, char, Overloaded binary search method to search a key
short, int, long, float, double, and Object. in the array of byte, char, short, int, long, float,
+binarySearch(a: xType[], key: xType): int double, and Object
Overloaded equals method for boolean, byte, Overloaded equals method that returns true if a is
char, short, int, long, float, double, and Object. equal to a2 for a and a2 of the boolean, byte, char,
+equals(a: xType[], a2: xType[]): boolean short, int, long, float, and Object type
Overloaded fill method for boolean char, byte, Overloaded fill method to fill in the specified
short, int, long, float, double, and Object. value into the array of the boolean, byte, char,
+fill(a: xType[], val: xType): void short, int, long, float, and Object type
+fill(a: xType[], fromIndex: int, toIndex: xType,
val: xType): void
Overloaded sort method for char, byte, short, int, Overloaded sort method to sort the specified array
long, float, double, and Object. of the char, byte, short, int, long, float, double,
+sort(a: xType[]): void and Object type
+sort(a: xType[], fromIndex: int, toIndex: int):
void
Convert to and from an Array
import java.util.*;
public class G{
public static void main(String[] args){
System.out.println();
Enhanced for loop
Output
1-first
2-second
3-third
Enhanced for loop
If a class extends Iterable<E>
(e.g. class Set<E> implements Iterable),
Java's enhanced for loop of this general form
for (E refVar : collection<E> ) {
refVar refers to each element in collection<E>
}
– example
ArrayList<String> list = new ArrayList<String>();
list.add("first");
for (String s : list)
System.out.println(s.toLowerCase());
Map and SortedMap
import java.util.*;
public class Test {
public static void main(String[] args) {
Set<String> ss = new LinkedHashSet<String>();
for (int i = 0; i < args.length; i++)
ss.add(args[i]);
Iterator i = ss.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
import java.util.*;
public class Test {
public static void main(String[] args)
{
//map to hold student grades
Map<String, Integer> theMap = new
HashMap<String, Integer>();
theMap.put("Korth, Evan", 100);
theMap.put("Plant, Robert", 90);
theMap.put("Coyne, Wayne", 92);
theMap.put("Franti, Michael", 98);
theMap.put("Lennon, John", 88);
System.out.println(theMap);
System.out.println("------------------");
System.out.println(theMap.get("Korth,
Evan"));
System.out.println(theMap.get("Franti,
Michael")); }}
Using Sets to find duplicate elements
import java.util.*;
System.out.println(s.size() + "
distinct words: " + s);
}}
Which class should I use?
The difference between the different classes is how the
structure is implemented.
This generally has an impact on performance.
Use Vector
Fast access to elements using index
Optimized for storage space
Not optimized for inserts and deletes
Use ArrayList
Same as Vector except the methods are not synchronized.
Better performance
Use linked list
Fast inserts and deletes
Stacks and Queues (accessing elements near the beginning
or end)
Not optimized for random access
Which class should I use?
Use Sets
When you need a collection which does not allow duplicate entries
Use Maps
Very Fast access to elements using keys
Fast addition and removal of elements
No duplicate keys allowed