0% found this document useful (0 votes)
71 views29 pages

Lists, Stacks, and Queues

This document provides an overview of lists, stacks, and queues in Java. It describes key interfaces like List and Collection in the Java Collections Framework hierarchy. It explains the differences between ArrayList and LinkedList, and when each might be used. The document also covers sorting and comparing elements using the Comparable and Comparator interfaces, and using utility methods in the Collections class. It defines stacks and the Stack class, and relationships between queues, lists and priority queues.

Uploaded by

s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views29 pages

Lists, Stacks, and Queues

This document provides an overview of lists, stacks, and queues in Java. It describes key interfaces like List and Collection in the Java Collections Framework hierarchy. It explains the differences between ArrayList and LinkedList, and when each might be used. The document also covers sorting and comparing elements using the Comparable and Comparator interfaces, and using utility methods in the Collections class. It defines stacks and the Stack class, and relationships between queues, lists and priority queues.

Uploaded by

s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter 8 Lists, Stacks, and

Queues

1
Objectives
 To explore the relationship between interfaces and classes in the
Java Collections Framework hierarchy (§20.2).
 To explore how and when to use ArrayList or LinkedList to store
elements (§20.4).
 To compare elements using the Comparable interface and the
Comparator interface (§20.5).
 To use the static utility methods in the Collections class for
sorting, searching, shuffling lists, and finding the largest and
smallest element in collections (§20.6).
 To distinguish between Vector and ArrayList and to use the Stack
class for creating stacks (§20.8).
 To explore the relationships among Collection, Queue,
LinkedList, and PriorityQueue and to create priority queues
using the PriorityQueue class (§20.9).
2
What is Data Structure?
 A data structure is a collection of data
organized in some fashion.
 The structure not only stores data, but also
supports operations for accessing and
manipulating the data.

3
Java Collection Framework
hierarchy
 A collection is a container object that
holds a group of objects, often referred to
as elements.
 The Java Collections Framework supports
three types of collections, named lists,
sets, and maps.

4
Java Collection Framework
hierarchy, cont.
 Set and List are subinterfaces of Collection.

5
The List Interface
 A list stores elements in a sequential
order, and allows the user to specify
where the element is stored.
 The user can access the elements by
index.
 The ArrayList class and the LinkedList
class are concrete implementations of the
List interface.
6
ArrayList vs. LinkedList
 If you need to support random access through
an index without inserting or removing elements
from any place other than the end, ArrayList
offers the most efficient collection.
 If, however, your application requires the
insertion or deletion of elements from any place
in the list, you should choose LinkedList.
 Study ListsPerformanceTest.java.

7
Array List Animation
https://liveexample.pearsoncmg.com/dsanimation/ArrayListeBook.htm
l

8
Linked List Animation
https://liveexample.pearsoncmg.com/dsanimation/LinkedListeBook.htm
l

9
java.util.ArrayList

«interface»
java.util.Collection<E>

«interface»
java.util.List<E>

java.util.ArrayList<E>

+ArrayList() Creates an empty list with the default initial capacity.


+ArrayList(c: Collection<? extends E>) Creates an array list from an existing collection.
+ArrayList(initialCapacity: int) Creates an empty list with the specified initial capacity.
+trimToSize(): void Trims the capacity of this ArrayList instance to be the
list's current size.

10
java.util.ArrayList cont.
Some of the commonly used methods in ArrayList.

java.util.ArrayList<E>
+ArrayList() Creates an empty list.
+add(o: E) : void Appends a new element o at the end of this list.
+add(index: int, o: E) : void Adds a new element o at the specified index in this list.
+clear(): void Removes all the elements from this list.
+contains(o: Object): boolean Returns true if this list contains the element o.
+get(index: int) : E Returns the element from this list at the specified index.
+indexOf(o: Object) : int Returns the index of the first matching element in this list.
+isEmpty(): boolean Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int Returns the index of the last matching element in this list.
+remove(o: Object): boolean Removes the element o from this list.
+size(): int Returns the number of elements in this list.
+remove(index: int) : boolean Removes the element at the specified index.
+set(index: int, o: E) : E Sets the element at the specified index.

11
java.util.LinkedList
«interface»
java.util.Collection<E> Some of the commonly used
methods in LinkedList.
«interface»
java.util.List<E>

java.util.LinkedList<E>

+LinkedList() Creates a default empty linked list.


+LinkedList(c: Collection<? extends E>) Creates a linked list from an existing collection.
+addFirst(o: E): void Adds the object to the head of this list.
+addLast(o: E): void Adds the object to the tail of this list.
+getFirst(): E Returns the first element from this list.
+getLast(): E Returns the last element from this list.
+removeFirst(): E Returns and removes the first element from this list.
+removeLast(): E Returns and removes the last element from this list.

12
Example: Using ArrayList and
LinkedList
 This example creates an array list filled with
numbers, and inserts new elements into the
specified location in the list.
 The example also creates a linked list from the
array list, inserts and removes the elements
from the list.
 Finally, the example traverses the list forward
and backward.
 Study TestArrayListLinkedList.java.
13
Array vs. List
 A list can grow or shrink its size
dynamically.
 The size of an array is fixed once it is
created.
 If your application does not require rapid
insertion or deletion of elements, the most
efficient data structure is the array.

14
The Comparator Interface
 Comparators allow us to add different methods
of comparing objects on top of Comparable
interface.
 For example, String defines Comparable
interface to compare strings based on
alphabetical order. We can define Comparator
to compare strings by length.

15
The Comparator Interface, cont.
 We also define a comparator if the objects to
compare are not instances of Comparable and
we don't have access to the source code.
 To define a comparator, define a class that
implements the java.util.Comparator
interface.

16
The Comparator Interface, cont.
 TheComparator interface has compare()
method for comparing two objects.
public int compare(Object element1,
Object element2)

 The compare() method should return:


– a negative value if element1 is less than element2
– a positive value if element1 is greater than
element2
– zero if they are equal.

17
The Comparator Interface, cont.
 Study SortStringByLength.java.
public static class MyComparator implements
java.util.Comparator<String> {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}

SortStringByLength

18
The Comparator Interface, cont.
 Study GeometricObjectComparator.java and
TestComparator.java.

if (area1 < area2)


return -1;
else if (area1 == area2)
return 0;
else
return 1;

GeometricObjectComparator TestComparator

19
The Collections Class
 The Collections class contains various static methods for
operating on collections and maps.

20
The Collections Class
 To sort a collection in ascending order,
List<String> list = Arrays.asList("red", "green", "blue");
Collections.sort (list);

 To sort a collection in descending order,


Collections.sort (list, Collections.reverseOrder());

 To shuffle a collection,
Collections.shuffle (list);

 To find the largest element in a collection,


String max = Collections.max (list);

21
The Stack Class
 The Stack class represents a last-in-first-out stack of
objects. The elements are accessed only from the top of
the stack.
 You can retrieve, insert, or remove an element from the
top of the stack.
java.util.Vector<E>  Vector is the same as ArrayList, except that
Vector contains the synchronized methods
java.util.Stack<E> for accessing and modifying the vector.

+Stack() Creates an empty stack.


+empty(): boolean Returns true if this stack is empty.
+peek(): E Returns the top element in this stack.
+pop(): E Returns and removes the top element in this stack.
+push(o: E) : E Adds a new element to the top of this stack.
+search(o: Object) : int Returns the position of the specified element in this stack.
22
Stack's Push and Pop

23
Stack Animation
https://liveexample.pearsoncmg.com/dsanimation/StackeBook.html

24
Using Stack
 What is the output off the following program?
Stack<String> stack = new Stack<>();
stack.push("Oklahoma");
stack.push("Indiana");
stack.push("Georgia");
stack.push("Texas");

while (stack.size() > 0)


System.out.print(stack.pop() + " ");

25
Queues
 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.

26
Queue Animation
https://liveexample.pearsoncmg.com/dsanimation/QueueeBook.html

27
Using LinkedList for Queue
 LinkedList is ideal for queue operations because
it is efficient for inserting and removing elements
from both ends of a list.
 What is the output off the following program?

Queue<String> queue = new LinkedList<>();


queue.offer("Oklahoma");
queue.offer("Indiana");
queue.offer("Georgia");
queue.offer("Texas");

while (queue.size() > 0)


System.out.print(queue.remove() + " ");

28
The PriorityQueue Class
 In a priority queue, the element with the highest priority
is removed first.
 The priority can be based on a Comparable
implementation or a custom Comparator.
 Study PriorityQueueDemo.java.
 What is the output off the following program?

PriorityQueue<String> queue1 = new PriorityQueue<>();


queue1.offer("Oklahoma");
queue1.offer("Indiana");
queue1.offer("Georgia"); PriorityQueueDemo
queue1.offer("Texas");
while (queue1.size() > 0) {
System.out.print(queue1.remove() + " ");
}

29

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy