0% found this document useful (0 votes)
15 views

Day 07 - Collections, Stack and Queue

Uploaded by

xuantae1030
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Day 07 - Collections, Stack and Queue

Uploaded by

xuantae1030
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Collections, Stack and Queue

Faculty of Information Technology, Hanoi University


What You Are About To Achieve 2
❖ By the end of this lecture, we are going to:
❑ Understand the core concepts of the Java Collection and its role in managing groups of objects.
❑ Differentiate between different types of collections:
➢ Lists (e.g., ArrayList, LinkedList)
➢ Sets (e.g., HashSet, TreeSet, SortedSet)
➢ Maps (e.g., HashMap, TreeMap)
➢ Queues (e.g., LinkedList, PriorityQueue)
➢ Stacks (e.g., Stack class)
❑ Explore the List interface and its implementations, focusing on: ArrayList - LinkedList
❑ Analyze the behavior of Set implementations:
➢ HashSet (unordered)
➢ TreeSet and SortedSet (ordered)
❑ Compare how Map structures store key-value pairs, understanding: HashMap - TreeMap
❑ Explain how Queue and Stack work for first-in, first-out (FIFO) and last-in, first-out (LIFO) scenarios
respectively.
❑ Apply the knowledge of these collections through practical code examples, emphasizing use cases for
each data structure.
3
❖ Introduction to Collections
❖ Lists
❖ Stacks
❖ Queues
❖ Sets
❖ Maps
❖ Final Touches
Introduction to Collections 4
❖ Before diving deeper into Collections, let’s first consider this problem:
Imagine we’re managing event attendees. We know we need to add names,
check if someone is attending, maybe remove names, and sometimes sort
the list of attendees.

We might try using arrays because that's what we've


worked with previously, right? But what happens when the
array is full, and more people show up? Or when we want
to remove someone, which means shifting elements
manually? Suddenly, managing this becomes a bit messy.
Introduction to Collections 5
❖ Before diving deeper into Collections, let’s first consider this problem:
Imagine we’re managing event attendees. We know we need to add names,
check if someone is attending, maybe remove names, and sometimes sort
the list of attendees.

Fortunately, Java provides us with something powerful called


Collections. Collections allow us to do all these things —
adding, removing, searching, and sorting — more easily and
efficiently. We don't need to worry about how many attendees
will show up or handle complex array manipulations.
Introduction to Collections 6
❖ Any group of individual objects that are represented as a single unit is known as a Java
Collection of Objects. In Java, a separate framework named the “Collection Framework”
has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface.
❖ There are two main “root” interfaces of Java collection classes:
❑ The Collection interface (java.util.Collection)
❑ The Map interface (java.util.Map)

Store elements Store key/value pairs


Introduction to Collections 7
❖ The Collection interface is the root interface for manipulating a collection of objects. Its
public methods are listed below:
Introduction to Collections 8
❖ The Collection interface provides the basic operations for adding and removing elements
in a collection:
❑ The add method adds an element to the collection.
❑ The addAll method adds all the elements in the specified collection to this collection.
❑ The remove method removes an element from the collection.
❑ The removeAll method removes the elements from this collection that are present in
the specified collection.
❑ The retainAll method retains the elements in this collection that are also present in
the specified collection.
❖ All these methods return boolean. The return value is true if the collection is changed as
a result of the method execution.
❖ The clear method simply removes all the elements from the collection.
Introduction to Collections 9
❖ The Collection interface also provides various query operations:
❑ The size method returns the number of elements in the collection.
❑ The contains method checks whether the collection contains the specified element.
❑ The containsAll method checks whether the collection contains all the elements in
the specified collection.
❑ The isEmpty method returns true if the collection is empty.
❑ The toArray method returns an array representation for the collection.
Introduction to Collections 10
❖ The Collection interface methods is represented as follow:
Introduction to Collections 11
❖ And here is an example:
public class TestCollection {
public static void main(String[] args) {
ArrayList<String> collection1 = new ArrayList<>();
collection1.add("New York");
collection1.add("Atlanta");
collection1.add("Dallas");
collection1.add("Madison");
System.out.println("A list of cities in collection1:");
System.out.println(collection1);
System.out.println("\nIs Dallas in collection1? “ + collection1.contains("Dallas"));
collection1.remove("Dallas");
System.out.println("\n" + collection1.size() + " cities are in collection1 now");
Collection<String> collection2 = new ArrayList<>();
collection2.add("Seattle");
collection2.add("Portland");
collection2.add("Los Angles");
collection2.add("Atlanta");
System.out.println("\nA list of cities in collection2:");
System.out.println(collection2);
ArrayList<String> c1 = (ArrayList<String>)(collection1.clone());
c1.addAll(collection2); // Add all elements in collection2 to c1
System.out.println("\nCities in collection1 or collection2: ");
System.out.println(c1);
c1 = (ArrayList<String>)(collection1.clone());
c1.retainAll(collection2);
System.out.print("\nCities in collection1 and collection2: ");
System.out.println(c1);
c1 = (ArrayList<String>)(collection1.clone());
c1.removeAll(collection2);
System.out.print("\nCities in collection1, but not in 2: ");
System.out.println(c1);
}
}
Introduction to Collections 12
❖ Furthermore, each collection is Iterable, which means you can obtain its Iterator object to traverse all the
elements in the collection.
❖ Iterator is a classic design pattern for walking through a data structure without having to expose the
details of how data is stored in the data structure. The Collection interface extends the Iterable interface.
The Iterable interface defines the iterator method, which returns an iterator. The Iterator interface
provides a uniform way for traversing elements in various types of collections:
❑ The iterator() method returns an instance of Iterator, which provides sequential access to the
elements in the collection using the next() method.
❑ You can also use the hasNext() method to check whether there are more elements in the iterator, and
the remove() method to remove the last element returned by the iterator.
Introduction to Collections 13
❖ And here is an example:
import java.util.*;
public class TestIterator {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<String>();
collection.add("New York");
collection.add("Atlanta");
collection.add("Dallas");
collection.add("Madison");

Iterator<String> iterator = collection.iterator();


while (iterator.hasNext()) {
System.out.print(iterator.next().toUpperCase() + " ");
}
System.out.println();
}
}
Introduction to Collections 14
❖ Have a look at this code again:
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next().toUpperCase() + " ");
}

❖ 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,

Is there any questions?

15
16

Uhm… Good job! Then, you know, while the


Collection interface provides the foundation for
handling groups of objects, it doesn't fully cater to
scenarios where the order of elements or the
ability to access them by index is critical.
17

Fortunately, Java provides List, which allows you to maintain the


order of elements and even store duplicates, which makes it ideal for
scenarios where the sequence matters, like task management or user
histories. What sets a List apart is its ability to access, update, or
remove elements by their index, something a general Collection can't
do. To implement a List, you typically use one of its two popular
classes: ArrayList or LinkedList, depending on your needs.
18
❖ Introduction to Collections
❖ Lists
❖ Stacks
❖ Queues
❖ Sets
❖ Maps
❖ Final Touches
Lists 19
❖ ArrayList and LinkedList are defined under the List interface. The List interface extends
Collection to define an ordered collection with duplicates allowed. The List interface
adds position-oriented operations, as well as a new list iterator that enables the user to
traverse the list bidirectionally. The methods introduced in the List interface are shown
below:
Lists 20
❖ The ArrayList class and the LinkedList class are two concrete implementations of the List
interface. ArrayList stores elements in an array. The array is dynamically created. If the
capacity of the array is exceeded, a larger new array is created and all the elements from
the current array are copied to the new array. LinkedList stores elements in a linked list.
Which of the two classes you use depends on your specific needs.

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.*;

public class TestStaticMethods {


public static void main(String[] args) {
List<String> list = Arrays.asList("yellow", "red", "green", "blue");
Collections.reverse(list);
System.out.println(list);
List<String> list1 = Arrays.asList("yellow", "red", "green", "blue");
List<String> list2 = Arrays.asList("white", "black");
Collections.copy(list1, list2);
System.out.println(list1);
Collection<String> c1 = Arrays.asList("red", "cyan");
Collection<String> c2 = Arrays.asList("red", "blue");
Collection<String> c3 = Arrays.asList("pink", "tan");
System.out.println(Collections.disjoint(c1, c2));
System.out.println(Collections.disjoint(c1, c3));
Collection<String> collection = Arrays.asList("red", "cyan", "red");
System.out.println(Collections.frequency(collection, "red"));
}
}
That’s all about Lists,

Is there any questions?

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;

public class StackExample {


public static void main(String[] args) {
// Create a new stack
Stack<Integer> stack = new Stack<>();

// Push elements onto the stack


stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);

// Pop elements from the stack


while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
33

In contrast of last-in-first-out, Java


provides another data structure
following first-in-first-out.
It’s called Queue…
34
❖ Introduction to Collections
❖ Lists
❖ Stacks
❖ Queues
❖ Sets
❖ Maps
❖ Final Touches
Queues 35
❖ A queue is a first-in, first-out data structure. Elements are appended to the end of the
queue and are removed from the beginning of the queue. In a priority queue, elements
are assigned priorities. When accessing elements, the element with the highest priority is
removed first. The Queue interface extends java.util.Collection with additional insertion,
extraction, and inspection operations, as shown below:
The offer method is used to add an element to the queue. This
method is similar to the add method in the Collection interface,
but the offer method is preferred for queues. The poll and remove
methods are similar, except that poll() returns null if the queue is
empty, whereas remove() throws an exception. The peek and
element methods are similar, except that peek() returns null if the
queue is empty, whereas element() throws an exception.
Queues 36
❖ And here is an example of Queue:
37
Nobita
Wow, stacks and queues make organizing data so much easier! First In,
First Out with queues and Last In, First Out with stacks - both are pretty
cool. But both stacks and queues still let you have duplicate elements,
right? Then, what if I don’t want duplicates at all?

Uhm let me see… Ah, there is something called Sets


in Java. Unlike stacks and queues, sets automatically
avoid duplicates and only store unique values..
Nobita Delivered
Set? What is it?

Yeah, Let me explain in detailed…


Delivered
38
❖ Introduction to Collections
❖ Lists
❖ Stacks
❖ Queues
❖ Sets
❖ Maps
❖ Final Touches
Sets 39
❖ A set is an efficient data structure for storing and processing nonduplicate elements. The Set interface
extends the Collection interface. It does not introduce new methods or constants, but it ensures that an
instance of Set contains no duplicate elements. The concrete classes that implement Set must ensure that
no duplicate elements can be added to the set. That is, no two elements e1 and e2 can be in the set such
that e1.equals(e2) is true.
❖ The AbstractSet class extends AbstractCollection and partially implements Set. The AbstractSet class
provides concrete implementations for the equals method and the hashCode method. The hash code of a
set is the sum of the hash codes of all the elements in the set. Since the size method and iterator method
are not implemented in the AbstractSet class, AbstractSet is an abstract class.
❖ There are three concrete classes of Set: HashSet, LinkedHashSet, and TreeSet
Sets - HashSet 40
❖ The HashSet class is a concrete class that implements Set. You can create an empty hash
set using its no-arg constructor or create a hash set from an existing collection. By
default, the initial capacity is 16 and the load factor is 0.75. If you know the size of your
set, you can specify the initial capacity and load factor in the constructor. Otherwise, use
the default setting. The load factor is a value between 0.0 and 1.0. For example,
// Creating an empty HashSet
HashSet<String> h = new HashSet<String>();

// Adding elements into HashSet


h.add("India");
h.add("Australia");
h.add("South Africa");

// Adding duplicate elements


h.add("India");
Sets - LinkedHashSet 41
❖ The LinkedHashSet extends HashSet with a linked-list implementation that supports an
ordering of the elements in the set. The elements in a HashSet are not ordered, but the
elements in a LinkedHashSet can be retrieved in the order in which they were inserted
into the set. A LinkedHashSet can be created by using one of its four constructors. These
constructors are similar to the constructors for HashSet. For example,
Sets - TreeSet 42
❖ The SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted.
Additionally, it provides the methods first() and last() for returning the first and last elements in the set,
and headSet(toElement) and tailSet(fromElement) for returning a portion of the set whose elements are
less than toElement and greater than or equal to fromElement, respectively. TreeSet implements the
SortedSet interface. To create a TreeSet, use a constructor. You can add objects into a tree set as long as
they can be compared with each other. For example,
public class TestTreeSet {
public static void main(String[] args) {
// Creating a Set interface with reference to TreeSet class
// Declaring object of string type
Set<String> ts = new TreeSet<>();

// Elements are added using add() method


ts.add("JSD");
ts.add("For");
ts.add("FITers");

// Print all elements inside object


System.out.println(ts); // Print: [FITers, For, JSD]
}
}
43
Nobita
Okay, so sets are great when you want to avoid
duplicates. But what if I need to not only store unique
values, but also associate each value with something else,
like a name with a phone number or an email?

Ah, you’re thinking about something where you need pairs of


related information, right? For that, you’d use a map. A map
allows you to store key-value pairs. Each key is unique, just like in
sets, but now each key is associated with a specific value.
Nobita
Delivered
Map? instead of just a list of unique
items, I can link items together?

Yeah, Exactly! A map is perfect when you want to create


relationships between data, like associating names with
phone numbers or product IDs with prices.
Delivered
44
❖ Introduction to Collections
❖ Lists
❖ Stacks
❖ Queues
❖ Sets
❖ Maps
❖ Final Touches
Maps 45
❖ A map is a container object that stores a collection of key/value pairs. It enables fast
retrieval, deletion, and updating of the pair through the key. A map stores the values
along with the keys. The keys are like indexes. In List, the indexes are integers. In Map,
the keys can be any objects. A map cannot contain duplicate keys. Each key maps to one
value. A key and its corresponding value form an entry stored in a map.
Maps 46
❖ And, similar to Sets, Maps have
three concrete implementations,
which are HashMap,
LinkedHashMap, and TreeMap.
Maps – HashMap, LinkedHashMap 47
❖ The HashMap class is efficient for locating a value, inserting an entry, and deleting an
entry.
❖ The LinkedHashMap extends HashMap with a linked-list implementation that supports an
ordering of the entries in the map. The entries in a HashMap are not ordered, but the
entries in a LinkedHashMap can be retrieved either in the order in which they were inserted
into the map (known as the insertion order) or in the order in which they were last
accessed, from least recently to most recently accessed (access order). The no-arg
constructor constructs a LinkedHashMap with the insertion order. To construct a
LinkedHashMap with the access order, use LinkedHashMap(initialCapacity, loadFactor, true).
Maps - HashMap 48
❖ Here is an example of HashMap:
Maps - LinkedHashMap 49
❖ Here is an example of LinkedHashMap:
Maps - LinkedHashMap 50
❖ The TreeMap class is efficient for traversing the keys in a sorted order. The keys can be sorted using the
Comparable interface or the Comparator interface. If you create a TreeMap using its no-arg constructor,
the compareTo method in the Comparable interface is used to compare the keys in the map, assuming that
the class for the keys implements the Comparable interface. To use a comparator, you have to use the
TreeMap(Comparator comparator) constructor to create a sorted map that uses the compare method in
the comparator to order the entries in the map based on the keys. For example,
public class TestTreeMap {
public static void main(String[] args) {
TreeMap<String, Integer> treeMap = new TreeMap<>();

// Adding key-value pairs to TreeMap


treeMap.put("Apple", 50);
treeMap.put("Banana", 30);
treeMap.put("Cherry", 20);
treeMap.put("Date", 40);

// Displaying the TreeMap (keys will be sorted)


System.out.println("TreeMap: " + treeMap);

// Accessing a value using a key


System.out.println("Price of Banana: " + treeMap.get("Banana"));
}
}
Summary 51
1. The Java Collections Framework supports sets, lists, queues, and maps. They are
defined in the interfaces Set, List, Queue, and Map.
2. A list stores an ordered collection of elements.
3. All the concrete classes except PriorityQueue in the Java Collections Framework
implement the Cloneable and Serializable interfaces. Thus, their instances can be cloned
and serialized.
4. To allow duplicate elements to be stored in a collection, you need to use a list. A list not
only can store duplicate elements but also allows the user to specify where they are
stored. The user can access elements by an index.
5. Two types of lists are supported: ArrayList and LinkedList. ArrayList is a resizable-array
implementation of the List interface. All the methods in ArrayList are defined in List.
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.
Summary 52
6. Comparator can be used to compare the objects of a class that doesn’t implement
Comparable.
7. The Vector class extends the AbstractList class. Starting with Java 2, Vector has been
the same as ArrayList, except that the methods for accessing and modifying the vector
are synchronized. The Stack class extends the Vector class and provides several
methods for manipulating the stack.
8. The Queue interface represents a queue. The PriorityQueue class implements Queue
for a priority queue.
9. A set stores nonduplicate elements. To allow duplicate elements to be stored in a
collection, you need to use a list.
10.A map stores key/value pairs. It provides a quick lookup for a value using a key.
11.Three types of sets are supported: HashSet, LinkedHashSet, and TreeSet. HashSet stores
elements in an unpredictable order. LinkedHashSet stores elements in the order they were
inserted. TreeSet stores elements sorted. All the methods in HashSet, LinkedHashSet, and
TreeSet are inherited from the Collection interface.
Summary 53
12. The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integers.
In Map, the keys can be any objects. A map cannot contain duplicate keys. Each key can map to at most
one value. The Map interface provides the methods for querying, updating, and obtaining a collection of
values and a set of keys.
13. Three types of maps are supported: HashMap, LinkedHashMap, and TreeMap. HashMap is efficient for
locating a value, inserting an entry, and deleting an entry. LinkedHashMap supports ordering of the
entries in the map. The entries in a HashMap are not ordered, but the entries in a LinkedHashMap can be
retrieved either in the order in which they were inserted into the map (known as the insertion order) or in
the order in which they were last accessed, from least recently accessed to most recently (access order).
TreeMap is efficient for traversing the keys in a sorted order. The keys can be sorted using the
Comparable interface or the Comparator interface.
14. To define a data structure is essentially to define a class. The class for a data structure should use data
fields to store data and provide methods to support operations such as insertion and deletion.
15. To create a data structure is to create an instance from the class. You can then apply the methods on the
instance to manipulate the data structure, such as inserting an element into the data structure or deleting
an element from the data structure.
16. You learned how to implement a priority queue using a heap.
This brings us to the
end of this lecture!
It’s time for Final
Touches…

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!

You might also like