Professional Documents
Culture Documents
Lecture 9-10
Lecture 9-10
● To learn how to use the collection classes supplied in the Java library
● To use iterators to traverse collections
● To choose appropriate collections for solving programming problems
● To study applications of stacks and queues
iitulogo.12b10e7a
0eb7.png
Java Collections Framework
iitulogo.12b10e7a
0eb7.png
Java Collections Framework
● When you need to organize multiple objects in your program, you can
place them into a collection
● The ArrayList class as an example. It is one of many collection classes
that the standard Java library supplies
● Each interface type is implemented by one or more classes
iitulogo.12b10e7a
0eb7.png
Java Collections Framework
iitulogo.12b10e7a
0eb7.png
Java Collections Framework
iitulogo.12b10e7a
0eb7.png
The collection interfaces
´ The Map
This maps unique keys to values.
´ The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner
class of Map.
´ The SortedMap
This extends Map so that the keys are maintained in an ascending order.
´ Iterator
Iterator enables you to cycle through a collection, obtaining or
removing elements.
iitulogo.12b10e7a
0eb7.png
The collection interfaces
The Collection interface is the foundation upon which the collections
framework is built. It declares the core methods that all collections will
have.
Methods and Description:
´ boolean add(Object obj)
Adds obj to the invoking collection. Returns true if obj was added to the
collection. Returns false if obj is already a member of the collection, or if
the collection does not allow duplicates.
´ boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns true if the
operation succeeds (i.e., the elements were added). Otherwise, returns
false. iitulogo.12b10e7a
0eb7.png
The collection interfaces
´ void clear( )
Removes all elements from the invoking collection.
´ boolean contains(Object obj)
Returns true if obj is an element of the invoking collection. Otherwise, returns false.
´ boolean containsAll(Collection c)
Returns true if the invoking collection contains all elements of c. Otherwise, returns
false.
´ boolean equals(Object obj)
Returns true if the invoking collection and obj are equal. Otherwise, returns false.
´ int hashCode( )
Returns the hash code for the invoking collection.
´ boolean isEmpty( )
Returns true if the invoking collection is empty. Otherwise, returns false.
´ Iterator iterator( )
Returns an iterator for the invoking collection.
iitulogo.12b10e7a
0eb7.png
The collection interfaces
´ boolean remove(Object obj)
Removes one instance of obj from the invoking collection. Returns true if the element was
removed. Otherwise, returns false.
´ boolean removeAll(Collection c)
Removes all elements of c from the invoking collection. Returns true if the collection
changed.
´ boolean retainAll(Collection c)
Removes all elements from the invoking collection except those in c. Returns true if the
collection changed.
´ int size( )
Returns the number of elements held in the invoking collection.
´ Object[ ] toArray( )
´ Returns an array that contains all the elements stored in the invoking collection. The array
elements are copies of the collection elements.
´ Object[ ] toArray(Object array[ ])
´ Returns an array containing only those collection elements whose type matches that of array
iitulogo.12b10e7a
0eb7.png
The List Interface
iitulogo.12b10e7a
0eb7.png
Example
iitulogo.12b10e7a
0eb7.png
Lists and Sets
● Ordered List
● ArrayList
■ Stores a list of items in a dynamically sized array
○ LinkedList
■ Allows speedy insertion and removal of items from the list
iitulogo.12b10e7a
0eb7.png
Lists and Sets
● Unordered Sets
● HashSet
■ Uses hash tables to speed up finding, adding, and removing elements
○ TreeSet
■ Uses a binary tree to speed up finding, adding, and removing elements
iitulogo.12b10e7a
0eb7.png
Stacks and Queues
´ Another way of gaining efficiency in a collection is to reduce
the number of operations available
´ Two examples are:
´ Stack
´ Remembers the order of its elements, but it does not allow you to
insert elements in every position
´ You can only add and remove elements at the top
´ Queue
´ Add items to one end (the tail)
´ Remove them from the other end (the head)
´ Example: A line of people waiting for a bank teller
iitulogo.12b10e7a
0eb7.png
In a queue, you add items to one end (the tail) and remove them from
(the head). For example, you could keep a queue of books, adding requ
the tail and taking a book from the head whenever you have time to rea
We will discuss stacks and queues in Section 15.5.
A map keeps
Finally, a map manages associations between keys and values. Ev
associations map has an associated value. The map stores the keys, values, and th
between key and between them. For an example, consider a library that puts a bar code o
Maps value objects.
The program used to check books in and out needs to look up the bo
with each bar code. A map associating bar codes with books can solve t
see Figure 5. We will discuss maps in Section 15.4.
ISBN 978-0-471-79191-1
90000
9 780470 509481
ISBN 978-0-470-38329-2
´ Keys Values
code)
´ Values
´ The actual object that is associated with the key
iitulogo.12b10e7a
0eb7.png
The Collection Interface (1)
● List, Queue and Set are specialized interfaces that inherit from the Collection interface
○ All share the following commonly used methods
iitulogo.12b10e7a
0eb7.png
The Collection Interface (2)
iitulogo.12b10e7a
0eb7.png
in the sequence needs to be closed up by
moving all objects that come after it. Con-
versely, suppose an employee is added in
the middle of the sequence. Then all names
following the new hire must be moved Each node in a linked list is connected to the
Linked Lists
toward the end. Moving a large number of neighboring nodes.
elements can involve a substantial amount
list consists
mber of of processing time. A linked list structure
each of which avoids this movement.
ference to ● Linked listslist
A linked use references
uses tonodes.
a sequence of maintain
A nodean
is ordered listsstores
an object that of ‘nodes’
an element
t node.
and references○to theThe ‘head’ of
neighboring theinlist
nodes the references the first
sequence (see Figure 6). node
○ Each node has a value and a reference to the next node
When you insert a new node into a linked list, only the neighboring node references
need to be updated (see Figure 7).
iitulogo.12b10e7a
0eb7.png
Generic Linked Lists
LinkedList<String> employeeNames = . . .;
LinkedList<String>
LinkedList<Employee>
iitulogo.12b10e7a
0eb7.png
List Iterators
LinkedList<String> employeeNames = . . .;
ListIterator<String> iter = employeeNames.listIterator()
iitulogo.12b10e7a
0eb7.png
Using Iterators
iterator.next();
iterator.add(“J”);
Note that the generic type for the listIterator must match the generic type
of the LinkedList iitulogo.12b10e7a
0eb7.png
Iterator and ListIterator Methods
● Iterators allow you to move through a list easily
○ Similar to an index variable for an array
iitulogo.12b10e7a
0eb7.png
Iterators and Loops
´ Iterators are often used in while and “for-each” loops
´ hasNext returns true if there is a next element
´ next returns a reference to the value of the next element
while (iterator.hasNext())
{
String name = iterator.next(); for (String name : employeeNames)
// Do something with name {
} // Do something with name
}
iitulogo.12b10e7a
0eb7.png
ListDemo.java (2)
iitulogo.12b10e7a
0eb7.png
The Set Interface
iitulogo.12b10e7a
0eb7.png
Example
iitulogo.12b10e7a
0eb7.png
Sets
´ A set is an unordered collection
´ The collection does not keep track of the order in which elements have
been added
The SortedSet interface extends Set and declares the behavior of a set
sorted in an ascending order.
iitulogo.12b10e7a
0eb7.png
Example
iitulogo.12b10e7a
0eb7.png
Hash Table Concept
● Set elements are grouped into smaller collections of elements that share
the same characteristic
○ It is usually based on the result
of a mathematical calculation
on the contents that results
in an integer value 100
○ In order to be stored in a hash
table, elements must have
101
a method to compute their
integer values
iitulogo.12b10e7a
0eb7.png
hashCode
○ The method is called hashCode
■ If multiple elements have the same hash code, they are stored
in a Linked list
iitulogo.12b10e7a
0eb7.png
Tree Concept
iitulogo.12b10e7a
0eb7.png
TreeSet
´ Use TreeSet for classes that implement the Comparable interface
iitulogo.12b10e7a
0eb7.png
Iterators and Sets
´ Iterators are also used when processing sets
´ hasNext returns true if there is a next element
´ next returns a reference to the value of the next element
´ add via the iterator is not supported for TreeSet and HashSet
Iterator<String> iter = names.iterator();
while (iter.hasNext()) for (String name : names)
{ {
String name = iter.next(); // Do something with name
// Do something with name }
}
´ Note that the elements are not visited in the order in which you inserted them.
´ They are visited in the order in which the set keeps them:
´ Seemingly random order for a HashSet
´ Sorted order for a TreeSet
iitulogo.12b10e7a
0eb7.png
Working With Sets (1)
iitulogo.12b10e7a
0eb7.png
Working With Sets (2)
iitulogo.12b10e7a
0eb7.png
SpellCheck.java (1)
iitulogo.12b10e7a
0eb7.png
SpellCheck.java (2)
iitulogo.12b10e7a
0eb7.png