Collection Framework
Collection Framework
Collection Framework
Framework
Shahjahan Samoon
1
Collections
• A collection is a structured group of objects
2
The Java Collections Framework
• A collection — sometimes called a container — is simply an
object that groups multiple elements into a single unit.
3
The Java Collections Framework
A collections framework is a unified architecture for representing and
manipulating collections.
All collections frameworks contain the following:
4
Benefits of the JCF
5
Benefits of the JCF
6
The Java Collections Framework
• An array is a very useful type in Java but it has its restrictions:
• once an array is created it must be sized, and this size is fixed;
• it contains no useful pre-defined methods.
• Java comes with a group of generic collection classes that grow
as more elements are added to them, and these classes
provide lots of useful methods.
• This group of collection classes are referred to as the Java
Collections Framework.
• The classes in the JCF are all found in the java.util
package.
• Three important interfaces from this group are:
– List;
– Set;
– Map.
7
Types of Collection
• Java supplies several types of Collection:
– Set: cannot contain duplicate elements, order is not important
– SortedSet: like a Set, but order is important
– List: may contain duplicate elements, order is important
• Java also supplies some “collection-like” things:
– Map: a “dictionary” that associates keys with values, order is not
important
– SortedMap: like a Map, but order is important
• While you can get all the details from the Java API, you are
expected to learn (i.e. memorize):
– The signatures of the “most important” methods in each interface
– The most important implementations of each interface
8
The Collections hierarchy
9
Collections are ADTs
• Collections are one of the best-designed parts of Java, because
– They are elegant: they combine maximum power with maximum
simplicity
– They are uniform: when you know how to use one, you almost
know how to use them all
– You can easily convert from one to another
10
The Collection interface
• Much of the elegance of the Collections Framework
arises from the intelligent use of interfaces
• The Collection interface specifies (among many other
operations):
– boolean add(E o)
– boolean contains(Object o)
– boolean remove(Object o)
– boolean isEmpty()
– int size()
– Object[] toArray()
– Iterator<E> iterator()
• You should learn all the methods of the Collection
interface--all are important
11
The Iterator interface
• An iterator is an object that will return the elements of a
collection, one at a time
• interface Iterator<E>
– boolean hasNext()
• Returns true if the iteration has more elements
– E next()
• Returns the next element in the iteration
– void remove()
• Removes from the underlying collection the last element returned by
the iterator (optional operation)
12
The Set interface
• A set is a collection in which:
– There are no duplicate elements (according to equals), and
– Order is not important
• interface Set<E> implements Collection, Iterable
• The methods of Set are exactly the ones in Collection
• The following methods are especially interesting:
– boolean contains(Object o) // membership test
– boolean containsAll(Collection<?> c) //subset test
– boolean addAll(Collection<? extends E> c) // union
– boolean retainAll(Collection<?> c) // intersection
– boolean removeAll(Collection<?> c) // difference
• addAll, retainAll, and removeAll return true if the receiving set
is changed, and false otherwise
13
The List interface
• A list is an ordered sequence of elements
• interface List<E> extends Collection, Iterable
• Some important List methods are:
– void add(int index, E element)
– E remove(int index)
– boolean remove(Object o)
– E set(int index, E element)
– E get(int index)
– int indexOf(Object o)
– int lastIndexOf(Object o)
– ListIterator<E> listIterator()
• A ListIterator is like an Iterator, but has, in addition, hasPrevious and
previous methods
14
The SortedSet interface
• A SortedSet is a Set for which the order of elements is
important
• interface SortedSet<E>
implements Set, Collection, Iterable
• Two of the SortedSet methods are:
– E first()
– E last()
• More interestingly, only Comparable elements can be added to
a SortedSet, and the set’s Iterator will return these in sorted
order
• The Comparable interface is covered in a separate lecture
15
The Map interface
• A map is a data structure for associating keys and values
• Interface Map<K,V>
• The two most important methods are:
– V put(K key, V value) // adds a key-value pair to the map
– V get(Object key) // given a key, looks up the associated value
• Some other important methods are:
– Set<K> keySet()
• Returns a set view of the keys contained in this map.
– Collection<V> values()
• Returns a collection view of the values contained in this map
16
The SortedMap interface
• A sorted map is a map that keeps the keys in sorted order
• Interface SortedMap<K,V>
• Two of the SortedMap methods are:
– K firstKey()
– K lastKey()
• More interestingly, only Comparable elements can be used as
keys in a SortedMap, and the method Set<K> keySet() will
return a set of keys whose iterator will return them sorted
order
• The Comparable interface is covered in a separate lecture
17
Some implementations
• class HashSet<E> implements Set
• class TreeSet<E> implements SortedSet
• class ArrayList<E> implements List
• class LinkedList<E> implements List
• class Vector<E> implements List
– class Stack<E> extends Vector
• Important methods: push, pop, peek, isEmpty
• class HashMap<K, V> implements Map
• class TreeMap<K, V> implements SortedMap
18
The List interface
• The List interface specifies the methods required to process
an ordered list of objects.
• Such a list may contain duplicates.
19
Using an ArrayList to store a
queue of jobs waiting for a printer
21
List methods - add
The List interface defines two add methods for inserting
into a list
– one inserts the item at the end of the list;
– the other inserts the item at a specified position in the
list.
We wish to use the first add method
This add method requires one parameter, the object to be
added into the list:
22
List methods - toString
All the Java collection types have a toString method
defined
So we can display the entire list to the screen:
23
List methods – add revisited
The add method is overloaded to allow an item to be
inserted into the list at a particular position.
24
List methods – set
• If we wish to overwrite an item in the list, rather
than insert a new item into the list, we can use
the set method.
• The set method requires two parameters, the
index of the item being overwritten and the new
object to be inserted at that position.
• Let us change the name of the last job from
"chapter.doc", to "newChapter.doc".
25
List methods – size
26
List methods – indexOf
27
List methods – remove
Items can be removed either by specifying an index or an
object.
When an item is removed, items behind this item shuffle to
the left
Example : removing "myFoto.jpg"
29
List methods – contains
30
List methods – isEmpty
• The isEmpty method reports on whether or not the list
contains any items
Using the enhanced ‘for’ loop with collection
classes
• The enhanced for loop can be used with the List (and Set)
implementations provided in the JCF.
• For example, here an enhanced for loop is used to iterate
through the printQ list to find and display those jobs that
end with a “.doc” extension:
31
Sets
• set: A collection of unique values (no duplicates allowed)
that can perform the following operations efficiently:
– add, remove, search (contains)
"the"
"if" "of"
set.contains("to") "to"
"down" "from" true
"by" "she"
set.contains("be") "you" false
"in"
"why" "him"
set
32
Set implementation
• in Java, sets are represented by Set interface in java.util
33
Set methods
List<String> list = new ArrayList<String>();
...
Set<Integer> set = new TreeSet<Integer>(); // empty
Set<String> set2 = new HashSet<String>(list);
34
Set operations
addAll(collection) adds all elements from the given collection to this set
containsAll(coll) returns true if this set contains every element from given set
equals(set) returns true if given other set contains the same elements
iterator() returns an object used to examine set's contents (seen later)
removeAll(coll) removes all elements in the given collection from this set
retainAll(coll) removes elements not found in given collection from this set
toArray() returns an array of the elements in this set
35
Sets and ordering
• HashSet : elements are stored in an unpredictable order
Set<String> names = new HashSet<String>();
names.add("Jake");
names.add("Robert");
names.add("Marisa");
names.add("Kasey");
System.out.println(names);
// [Kasey, Robert, Jake, Marisa]
"Marty" true
Set
false
"Marty" "206-685-2181"
Map
38
keySet and values
• keySet method returns a Set of all keys in the map
– can loop over the keys in a foreach loop
– can get each key's associated value by calling get on the map
• This doesn't let us easily ask which TAs got a given GPA.
– How would we structure a map for that?
40
Reversing a map
• We can reverse the mapping to be from GPAs to names.
Map<Double, String> taGpa = new HashMap<Double, String>();
taGpa.put(3.6, "Jared");
taGpa.put(4.0, "Alyssa");
taGpa.put(2.9, "Steve");
taGpa.put(3.6, "Stef");
taGpa.put(2.9, "Rob");
...
System.out.println("Who got a 3.6? " +
taGpa.get(3.6)); // ???
– must be careful to initialize the set for a given GPA before adding
42
Iterators
43
Examining sets and maps
• elements of Java Sets and Maps can't be accessed by index
– must use a "foreach" loop:
Set<Integer> scores = new HashSet<Integer>();
for (int score : scores) {
System.out.println("The score is " + score);
}
index 0 1 2 3 4 5 6 7 8 9 "the"
list value 3 8 9 7 5 12 0 0 0 0 set "to" "we"
size 6 "from"
45
Iterator methods
hasNext() returns true if there are more elements to examine
next() returns the next element from the collection (throws a
NoSuchElementException if there are none left to examine)
remove() removes the last value returned by next() (throws an
IllegalStateException if you haven't called next() yet)
50
Map methods
put(key, value) adds a mapping from the given key to the given value;
if the key already exists, replaces its value with the given one
get(key) returns the value mapped to the given key (null if not found)
containsKey(key) returns true if the map contains a mapping for the given key
remove(key) removes any existing mapping for the given key
clear() removes all key/value pairs from the map
size() returns the number of key/value pairs in the map
isEmpty() returns true if the map's size is 0
toString() returns a string such as "{a=90, d=60, c=70}"
51
Using maps
• A map allows you to get from one half of a pair to the other.
– Remembers one piece of information about every index (key).
// key value
put("Marty", "206-685-2181")
Map
– Later, we can supply only the key and get back the related value:
Allows us to ask: What is Marty's phone number?
get("Marty")
Map
"206-685-2181"
52
keySet and values
• keySet method returns a set of all keys in the map
– can loop over the keys in a foreach loop
– can get each key's associated value by calling get on the map
54