Академический Документы
Профессиональный Документы
Культура Документы
Framework
© Luxoft Training 2013
Collections
Introduction
Many programs need to keep track of
groups of related data items
Arrays have some limitations:
You cannot change the size of an array after
construction
Arrays provide very simple mechanism for
storing and accessing the data
© Luxoft Training 2013
4-2
Collections
Introduction
Complex data structures are created
with the help of Java Collections
Framework
Collections are a mechanism for
manipulating object references. Arrays
are capable of storing primitives or
references, collections are not.
© Luxoft Training 2013
4-3
Collections
Introduction
The central interfaces of Java Collection
Framework are:
java.util.Collection
java.utils.List (extends
java.util.Collection)
java.utils.Set (extends
java.util.Collection)
java.utils.Map (does not extend
java.util.Collection)
© Luxoft Training 2013
4-4
Collections
Hierarchy of central interfaces
© Luxoft Training 2013
4-5
Collections
Hierarchy of central interfaces
© Luxoft Training 2013
4-6
Collections
The java.util.Collection interface
The java.util.Collection interface
is a core interface in the hierarchy
Collection is a group of objects called as
elements
Some collections allow duplicate elements
and others do not
Some are ordered and others are
© Luxoft Training 2013
unordered
4-7
Collections
The java.util.Collection interface
Method Description
add(Object x) Adds x to this collection
addAll(Collection c) Adds every element of c to this collection
clear() Removes every element from this collection
contains(Object x) Returns true if this collection contains x
containsAll(Collection Returns true if this collection contains every element of
c) с
isEmpty() Returns true if this collection contains no elements
iterator() Returns an Iterator over this collection
remove(Object x) Removes x from this collection
removeAll(Collection c) Removes every element in c from this collection
retainAll(Collection c) Removes from this collection every element that is not in
c
© Luxoft Training 2013
4-8
Collections
The java.util.Iterator interface
java.util.Collection extends
interface java.util.Iterable that
defines the iterator() method
This method returns the instance of
java.util.Iterator
Iterator allows to sort the elements of
the collection and takes the place of the
legacy interface Enumeration that was
© Luxoft Training 2013
4-10
Collections
The java.util.Iterator interface
public void dumpCollection(Collection c) {
System.out.println("Collection has" + c.size() +
" elements.");
Iterator iter = c.iterator();
while (iter.hasNext()) {
Object elem = iter.next()
System.out.println("Next element is" + elem);
if (getClause(elem)) {
iter.remove();
}
}
}
© Luxoft Training 2013
4-11
Collections
The java.util.List interface
A List keeps its elements in the order in
which they were added
Each element of a List has an index,
starting from 0
List is something like an array that grows
as needed
© Luxoft Training 2013
4-12
Collections
Additional java.util.List methods
void add(int index, Inserts x at index. The index of each subsequent
Object x element is increased by 1, so indices remain
sequential.
Object get(int Returns the element at index.
index)
int indexOf(Object
x) Returns the index of the first occurrence of x,
or -1 if the List does not contain x
Object remove(int
Removes the element at index
index)
© Luxoft Training 2013
4-13
Collections
java.util.List implementations
ArrayList – array-based list
implementation
Quick search
Slow growth, because array has to be copied for
the growth
Slow removal, because array has to be copied
for the shrink
© Luxoft Training 2013
4-14
ArrayList: add an element
© Luxoft Training 2013
ArrayList: insert an element
© Luxoft Training 2013
Collections
java.util.List implementations
java.util.LinkedList is a double-
linked list implementation
Slow search
Quick growth, as new elements can be
added without recopying right in the end of a
queue
© Luxoft Training 2013
4-17
© Luxoft Training 2013
LinkedList
LinkedList: add an element
© Luxoft Training 2013
LinkedList: add to the middle of
the list
© Luxoft Training 2013
Collections
Example:
LinkedOrArrayListTutor
© Luxoft Training 2013
4-21
Comparision of
ArrayList and LinkedList
iterations
4-23
Collections
The java.util.Set interface
If you try to add an object to a Set that
already contains that object, the add()
call will return false and the Set will not
be changed
Sets use the equals() method, not the
== operator, to check for duplication of
elements
© Luxoft Training 2013
4-24
Collections
The java.util.Set interface
void addTwice(Set set) {
set.clear();
Point p1 = new Point(10, 20);
Point p2 = new Point(10, 20);
set.add(p1);
set.add(p2);
System.out.println(set.size());
}
© Luxoft Training 2013
4-25
Collections
java.util.HashSet implementation
No matter how many elements a
HashSet contains, its basic operations
will always execute in constant time
HashSet stores elements in buckets
grouped by hashCode() value
© Luxoft Training 2013
4-26
© Luxoft Training 2013
HashSet
Collections
java.util.TreeSet implementation
The java.util.TreeSet
implementation guarantees that
elements enumerated by iterator()
will always be presented in sorted order
Amount of time required to access
elements is log(n), where n is the
number of elements in the set
© Luxoft Training 2013
4-28
Collections
java.util.TreeSet implementation
The java.util.SortedSet interface
extends java.util.Set and presents
sorted set of elements
Elements added to such a set are
resorted; java.util.SortedSet
allows to receive elements in a certain
order
© Luxoft Training 2013
4-29
Collections
TreeSet: binary tree
4-32
Collections
Example:
CollectionTutor
© Luxoft Training 2013
4-33
Collections
Example:
CollectionRemoveTutor
© Luxoft Training 2013
4-34
Collections
Compare elements
As far as TreeSet class supports
elements sorting it needs the mechanism
that would allow to compare two objects
The following interfaces can be used for
comparison:
java.lang.Comparable
java.util.Comparator
© Luxoft Training 2013
4-35
Collections
java.lang.Comparable
java.lang.Comparable defines
public int compareTo(Object x)
method. This one returns a positive
number if the current object is “greater
than” х and a negative number if the
current object is “less than” х , and 0 if
the current object is “equal to” х
© Luxoft Training 2013
4-36
Collections
java.lang.Comparable
All elements inserted to
java.util.TreeSet must implement
the Comparable interface
java.util.TreeSet allows for any
Object subclass to be inserted.
However, if the element doesn’t
implement Comparable the runtime will
throw ClassCastException
© Luxoft Training 2013
4-37
Collections
java.lang.Comparable
Many Core Java classes implement
Comparable (String, Date,
Integer)
Implementation of Comparable must
define so called natural ordering
For instance, lexicographical order for
strings
© Luxoft Training 2013
4-38
Collections
java.lang.Comparable
For the Student class the natural order
is not so evident, as students can be
sorted by names, last names, grades,
year of enrollment, etc.
When natural order can’t be used or
some other way of elements comparison
is needed use
java.util.Comparator
© Luxoft Training 2013
4-39
Collections
java.lang.Comparator
You can also define a class
implementing the java.util.
Comparator interface that compares
objects of the given type
Corresponding Comparator can be
passed to TreeSet using special
constructor
int compare(Object o1, Object
© Luxoft Training 2013
4-41
Collections
java.lang.Comparator
Example:
ComparableTutor
© Luxoft Training 2013
4-42
Collections
The java.util.Map interface
java.util.Map combines two
collections, called keys and values
Map associates exactly one value (it can be
null) with each key
Each key is used in Map only once
A good example is a dictionary
© Luxoft Training 2013
4-43
Collections
The java.util.Map interface
Object put(Object Associates key and value. If the Map already
key, Object value) associates a value with key, the old value is removed
and returned; otherwise it returns null.
Object get(Object Returns the value associated with key, or null if no
key) value is associated with key
boolean Returns true if the Map associates some value
containsKey(Object with key
key)
void clear() Empties the Map
Set keySet() Returns a Set containing the Map’s keys. Changes to
the Map will be reflected in the Set, and changes to the
Set will affect the Map, so it’s not a good idea to
modify the Set
Collection Returns a collection containing the Map’s values.
© Luxoft Training 2013
4-45
Collections
java.util.Map implementations
java.util.HashMap iterates keys in an
unpredictable order. Keys are quickly
accessed
The hashCode() method must be
overridden and must return uniformly
distributed integers
The equals() method is used to check if
the elements are equal (not ==)
© Luxoft Training 2013
4-46
Collections
Interior of HashMap
hash
code
5345
key object
With use of
indexFor
(hash, tableLength), defined
the position in the array,
where an element will be put:
}
length – cell
amount of address
cells
Collections
Interior of HashMap
Storage initialization in constructor.
Capacity has initial value 16
constructor
4-52
Collections
Interface java.util.SortedMap
Interface java.util.SortedMap extends
java.util.Map
Object firstKey() Returns this set’s first key
Object lastKey() Returns this set’s last key
SortedMap Returns a sorted Map containing this Map’s
headMap(Object toKey) mappings with keys up through the specified key
toKey
SortedMap Returns a sorted Map containing this Map’s map-
tailMap(Object pings from the specified key through the last key
fromKey) fromKey to the end
SortedMap Returns a sorted Map containing this Map’s
subMap(Object
© Luxoft Training 2013
4-53
Collections
Example
public class MapExample {
public static void main(String args[]) {
Map map = new HashMap();
map.put("one", "1st");
map.put("second", new Integer(2));
map.put("third", "3rd");
// Overwrites the previous assignment
map.put("third", "III");
// Returns set view of keys
Set set1 = map.keySet();
// Returns Collection view of values
Collection collection = map.values();
// Returns set view of key value mappings
Set set2 = map.entrySet();
© Luxoft Training 2013
Example:
MapTutor
© Luxoft Training 2013
4-55
Collections
Support classes
There are two support classes that
provide static methods that operate on
collections and arrays:
java.util.Collections
java.util.Arrays
© Luxoft Training 2013
4-56
Collections
Some java.util.Collections methods
static boolean Returns true if the two collections have no
disjoint(Collection elements in common
c1, Collection c2)
static int Returns the number of elements in c that are
frequency(Collection equal to ob
c, Object ob)
static Object Returns the maximum element of c according
max(Collection c) to the natural ordering of the elements
static Object Returns the maximum element of c according
min(Collection c) to the natural ordering of the elements
static void Reverses the order of the elements in the
reverse(List list) specified List
static void Randomly rearranges the List’s elements
shuffle(List list)
© Luxoft Training 2013
4-57
Collections
Some java.util.Arrays methods
static List Returns a list representing array arr. Changing an
asList(Object[] element in the List also changes the corresponding
arr) element of the array
static void Rearranges the List’s elements into their natural
sort(byte[] arr) order. This method is extensively overloaded, with
versions that take arrays of each primitive type, as
well as a version that takes an array of Object
static int Efficiently searches the array and returns the index
binarySearch(byte[] of key. The array’s elements must be sorted before
arr, byte key the method is called. This method is extensively
overloaded, with versions that take arrays and keys
of each primitive type, as well as a version that
takes an array of Object and an Object key
static boolean
© Luxoft Training 2013
4-58
Collections
Some java.util.Arrays methods
Example:
CollectionUtilitiesTutor
© Luxoft Training 2013
4-59
Collections
Legacy collections
Java Collections Framework was
introduced in Java 1.2
Before this, similar data structures
existed, but their behavior was not unified
All of their methods were synchronized,
which decreased performance
© Luxoft Training 2013
4-60
Collections
Legacy collections
The Vector class implements List. Use
ArrayList instead of Vector
The Stack class, a subclass of Vector
supports stack operations: push(), pop(),
peek()
The Hashtable class implements the Map
interface. Use the HashMap class instead of
Hashtable
© Luxoft Training 2013
4-61
Collections
Legacy collections
Each of these collections has the
elements()method that returns the
Enumeration object, which allows to iterate
elements in an iterator-like fashion
However, this class is not compatible with
Iterator
That is why it is not recommended to use
Enumeration
© Luxoft Training 2013
4-62
Collections
Synchronizing collections
All collections of Collections Framework
are not synchronized. In other words,
class methods are not labeled as
synchronized
This boosts the performance of single-
threaded program
© Luxoft Training 2013
4-63
Collections
Synchronizing collections
To get an instance of a synchronized collection,
invoke Collections.synchronizedXYZ(),
where XYZ is an interface: Set, List, Map,
Collection, etc.
At the same time a primitive delegate class is
created. All of its methods are synchronized and
delegate the invocation to proxied collection
© Luxoft Training 2013
4-64
Collections
Synchronizing collections. Example
List unsynch = new ArrayList();
List sync = Collections.synchronizedList(unsynch);
4-65
Collections
Unmodifiable collections
From the point of view of data
encapsulation it is incorrect to return a
collection instance from the class method,
as the client code can modify this collection
One way to solve this problem is to return a
collection’s copy. Only shallow copy will be
returned, without the contents
© Luxoft Training 2013
4-66
Collections
Unmodifiable collections
Another option is to call Collections.
unmodifiableXYZ that returns a simple
proxy class delegating the invocations to
unmodifiable methods (get(), size())
of the corresponding collection and
throwing
UnsupportedOperationException for
methods that modify the collection (e.g.
add(), remove())
© Luxoft Training 2013
4-67
Collections
Unmodifiable collections. Example
public class C {
private List clients;
List getClients() {
return Collections.unmodifiableList(clients);
}
}
© Luxoft Training 2013
4-68
Exercises
Lab guide:
• Exercise 1
• Exercise 2
• Exercise 3
© Luxoft Training 2013
4-69