Day 07 - Collections, Stack and Queue
Day 07 - Collections, Stack and Queue
❖ You know, you can simplify it using a foreach loop without using an iterator:
for (String element: collection)
System.out.print(element.toUpperCase() + " ");
❖ This loop is read as “for each element in the collection, do the following”. The foreach loop can be used
for arrays as well as any instance of Iterable.
That’s some key features of Collections,
15
16
Array List
Lists - ArrayList 21
❖ ArrayList is a resizable-array implementation of the List interface. It also provides
methods for manipulating the size of the array used internally to store the list. Each
ArrayList instance has a capacity, which is the size of the array used to store the elements
in the list. It is always at least as large as the list size. As elements are added to an
ArrayList, its capacity grows automatically. An ArrayList does not automatically shrink.
You can use the trimToSize() method to reduce the array capacity to the size of the list.
An ArrayList can be constructed using its no-arg constructor, ArrayList(Collection), or
ArrayList(initialCapacity).
Lists - ArrayList 22
❖ Here is an example of ArrayList:
Lists - LinkedList 23
❖ LinkedList is a linked list implementation of the List interface. In addition to
implementing the List interface, this class provides the methods for retrieving, inserting,
and removing elements from both ends of the list. A LinkedList can be constructed using
its no-arg constructor or LinkedList(Collection).
Lists - LinkedList 24
❖ And here is an example of LinkedList:
“Need more operations?
Let’s see what can you do with some following static methods...
25
Lists 26
❖ The Collections class contains the sort, binarySearch, reverse, shuffle, copy, and fill
methods for lists, and max, min, disjoint, and frequency methods for collections, as
shown below:
Lists 27
❖ To see how these methods work, try to run this code:
import java.util.*;
28
29
❖ Introduction to Collections
❖ Lists
❖ Stacks
❖ Queues
❖ Sets
❖ Maps
❖ Final Touches
Stacks 30
❖ The Java Collections Framework was introduced in Java 2. Several data structures were supported earlier,
among them, the Vector and Stack classes were redesigned to fit into the Java Collections Framework, but
all their old-style methods are retained for compatibility.
❖ Vector is the same as ArrayList, except that it contains synchronized methods for accessing and modifying
the vector. Synchronized methods can prevent data corruption when a vector is accessed and modified by
two or more threads concurrently. We will discuss synchronization later, in PR2, SE and JSD. For the
many applications that do not require synchronization, using ArrayList is more efficient than using Vector.
Stacks 31
❖ Besides, the Stack class was introduced as an extension of Vector. The class is based on
the basic principle of last-in-first-out. In addition to the basic push and pop operations,
the class provides three more functions of empty, search, and peek.
Stacks 32
❖ Here is an example of Stack:
import java.util.Stack;
54
Final Touches 55
❖ Collections
❑ The design of the Java Collections Framework is an excellent example of using interfaces, abstract
classes, and concrete classes. The interfaces define the framework. The abstract classes provide
partial implementation. The concrete classes implement the interfaces with concrete data structures.
Providing an abstract class that partially implements an interface makes it convenient for the user to
write the code. The user can simply define a concrete class that extends the abstract class rather
implements all the methods in the interface. The abstract classes such as AbstractCollection are
provided for convenience. For this reason, they are called convenience abstract classes.
❑ The methods addAll, removeAll, and retainAll are similar to the set union, difference, and
intersection operations.
❑ All the concrete classes in the Java Collections Framework implement the java.lang.
Cloneable and java.io.Serializable interfaces except that java.util.PriorityQueue does not
implement the Cloneable interface. Thus, all instances of Cloneable except priority queues can
be cloned and all instances of Cloneable can be serialized.
Final Touches 56
❖ ArrayList vs. LinkedList
❑ A list can hold identical elements. Integer 1 is stored twice in the list. ArrayList and LinkedList operate
similarly. The critical difference between them pertains to internal implementation, which affects their
performance. ArrayList is efficient for retrieving elements and LinkedList is efficient for inserting and
removing elements at the beginning of the list. Both have the same performance for inserting and
removing elements in the middle or at the end of the list.
❑ The get(i) method is available for a linked list, but it is a time-consuming operation. Do not use it to
traverse all the elements in a list as shown in (a). Instead you should use an iterator as shown in (b).
Note that a foreach loop uses an iterator implicitly.
Final Touches 57
❖ Comparator
❑ You can sort the comparable elements in a list in its natural order with the compareTo method in the
Comparable interface. You may also specify a comparator to sort elements. For example,
❑ Do not worry if you do not know how. You will soon see it in PR2. Thus, in this course, just use some
other useful methods.
Final Touches 58
❖ Deque
❑ The LinkedList class implements the Deque interface, which extends the Queue interface. Therefore,
you can use LinkedList to create a queue. LinkedList is ideal for queue operations because it is efficient
for inserting and removing elements from both ends of a list.
❑ Deque supports element insertion and removal at both ends. The name deque is short for “double-
ended queue” and is usually pronounced “deck.” The Deque interface extends Queue with additional
methods for inserting and removing elements from both ends of the queue. The methods addFirst(e),
removeFirst(), addLast(e), removeLast(), getFirst(), and getLast() are defined in the Deque interface.
Final Touches 59
❖ Priority Queues
❑ The PriorityQueue class implements a priority queue, as shown in Figure 20.14. By default, the priority
queue orders its elements according to their natural ordering using Comparable. The element with the
least value is assigned the highest priority and thus is removed from the queue first. If there are
several elements with the same highest priority, the tie is broken arbitrarily. You can also specify an
ordering using Comparator in the constructor PriorityQueue(initialCapacity, comparator).
Final Touches 60
❖ HashSet
❑ The load factor measures how full the set is allowed to be before its capacity is increased. When the
number of elements exceeds the product of the capacity and load factor, the capacity is automatically
doubled. For example, if the capacity is 16 and load factor is 0.75, the capacity will be doubled to 32
when the size reaches 12 (16*0.75 = 12). A higher load factor decreases the space costs but increases
the search time. Generally, the default load factor 0.75 is a good tradeoff between time and space
costs.
Final Touches 61
❖ Sorted Set
❑ NavigableSet extends SortedSet to provide navigation methods lower(e), floor(e), ceiling(e), and higher(e)
that return elements respectively less than, less than or equal, greater than or equal, and greater than a
given element and return null if there is no such element. The pollFirst() and pollLast() methods remove
and return the first and last element in the tree set, respectively.
Final Touches 62
❖ Maps
❑ SortedMap is a subinterface of Map, which guarantees that the entries in the map are sorted.
Additionally, it provides the methods firstKey() and lastKey() for returning the first and last keys in the
map, and headMap(toKey) and tailMap(fromKey) for returning a portion of the map whose keys are
less than toKey and greater than or equal to fromKey, respectively.
❑ NavigableMap extends SortedMap to provide the navigation methods lowerKey(key), floorKey(key),
ceilingKey(key), and higherKey(key) that return keys respectively less than, less than or equal, greater
than or equal, and greater than a given key and return null if there is no such key. The pollFirstEntry()
and pollLastEntry() methods remove and return the first and last entry in the tree map, respectively.
❑ All the concrete classes that implement the Map interface have at least two constructors. One is the
no-arg constructor that constructs an empty map, and the other constructs a map from an instance of
Map. Thus, new TreeMap<String, Integer>(hashMap) constructs a tree map from a hash map.
❑ You can create an insertion-ordered or access-ordered linked hash map. The most recently accessed
entry is placed at the end of the map.
63
Thanks!
Any questions?
For an in-depth understanding of Java, I highly recommend
referring to the textbooks. This slide provides a brief overview
and may not cover all the details you're eager to explore!