0% found this document useful (0 votes)
5 views37 pages

L15 ListsStacksQueues A (ch20)

The document discusses data structures in Java, focusing on Lists, Stacks, Queues, and Priority Queues, with an emphasis on the Collection Interface and its methods. It compares ArrayList and LinkedList, detailing their structures, methods, and performance characteristics. The document also provides examples and practical considerations for choosing between different types of lists.

Uploaded by

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

L15 ListsStacksQueues A (ch20)

The document discusses data structures in Java, focusing on Lists, Stacks, Queues, and Priority Queues, with an emphasis on the Collection Interface and its methods. It compares ArrayList and LinkedList, detailing their structures, methods, and performance characteristics. The document also provides examples and practical considerations for choosing between different types of lists.

Uploaded by

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

Data Structures

Lists, Stacks, Queues, and Priority Queues


Part 1/2
Dr. Mostafa Mohamed

Acknowledgement: The slides mainly rely on the textbook of Y. D. Liang titled “Introduction to
Java Programming, 10th Ed.”, Pearson Edu. Inc. COSC 121. Page 1
Previous Lecture
▪ Intro to the implementation of ArrayLists

▪ Iterating Over an ArrayList

▪ Useful Methods for Lists


• Arrays and Collections classes

▪ Intro to Generics

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 2
Outline
Today:
▪ Collection Interface

▪ Lists:
• ArrayList (again)

• LinkedList

• ArrayList vs LinkedList
• Big-Oh Notation

Next lecture:
▪ More Lists: Vector / Stack

▪ Queues: Queue / PriorityQueue

▪ Interfaces: Comparable / Comparator COSC 121. Page 3


Previously…

COSC 121. Page 4


Remember: Java Collections Framework
A data structure is a collection of data organized in some
fashion.
▪ It is a container object that stores other objects (data).
▪ To define a data structure is essentially to define a class.
• uses data fields to store data and methods to support operations for
accessing and manipulating the data.
▪ COSC 222

Java Collections Framework includes several data structures


for storing and managing data (objects of any type).
It supports two types of containers:
▪ collection: for storing a collection of elements.
• e.g. Sets (nonduplicates), Lists (ordered), Stacks (LIFO), Queues
(FIFO), PriorityQueues
▪ map: for storing key/value pairs.
• e.g., HashMap
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 5
Remember: Collection Class Hierarchy (accurate)

Interfaces Abstract Classes Concrete Classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 6
Remember: Collections Class Hierarchy
This diagram is not accurate. There are several abstract classes
and interfaces missing, but it should help in visualization

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 7
Collection

COSC 121. Page 8


Collections Class Hierarchy (simplified)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 9
The Collection Interface
The Collection interface is the root interface for manipulating
a collection of objects. It declares the methods for:

adding elements add , addAll

removing elements clear , remove , removeAll , retainAll

checking for elements contains , containsAll

checking for equality equals

checking the size size, isEmpty

returning as array toArray

returning an iterator* iterator

* by inheritance from Iterable

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 10
The Collection Interface

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 11
Example on Collection
ArrayList<String> c1 = new ArrayList<>(Arrays.asList("A","B","A","D"));
ArrayList<String> c2 = new ArrayList<>(Arrays.asList("A","X","Y","Z"));
System.out.println("c1: " + c1);
System.out.println("c2: " + c2); c1 A B A D

//cloning, checking and removing c2 A X Y Z


ArrayList<String> c3 = (ArrayList<String>) c1.clone();
System.out.println("Is B in c1? " + c3.contains("B")); //true
c3.remove("B");
System.out.println("Is B in c1? " + c3.contains("B")); //false

//addAll
c3 = (ArrayList<String>) c1.clone(); //restore c1 items
c3.addAll(c2); //add all c2 items to c3. Duplicates are allowed
System.out.println("Items in c1 and c2 combined: " + c3); //[A,B,A,D,A,X,Y,Z]

//removeAll
c3 = (ArrayList<String>) c1.clone(); //restore c1 items
c3.removeAll(c2); //remove all c2 items from c3
System.out.println("Items in c1 but not in c2: " + c3); //[B,D]

//retainAll
c3 = (ArrayList<String>) c1.clone(); //restore c1 items
c3.retainAll(c2); //keep items in c3 that are also in c1
System.out.println("Items in c1 (intersection) c2: " + c3); //[A,A]
COSC 121. Page 12
Lists

COSC 121. Page 13


Collections Class Hierarchy (simplified)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 14
List Interface
The List interface
▪ Ordered (each element has an index)
▪ Duplicates allowed.
Methods:
▪ All methods from Collection
▪ & iterator methods: listIterator()
▪ & index-based methods
• Adding add(index,element)
addAll(index, collection)
• Removing remove(index)
• Setting set(index, element)
• Getting get(index)
• Checking indexOf(element)
lastIndexOf(element)
• Sublist subList(fromIndex, toIndex)
Concrete classes
▪ ArrayList, LinkedList
ArrayList<E>
Methods:
▪ All methods from List
▪ & extra method
• trimToSize() Trims the capacity of this ArrayList instance
to be the list's current size.

Constructors
▪ ArrayList()
• Creates an empty list with default capacity.
▪ ArrayList(int initialCapacity)
▪ ArrayList(c: Collection<? extends E>)
• Create ArrayList from an existing collection of any subtype of E

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 16
LinkedList<E>
Methods:
▪ All methods from List
▪ & extra methods specifically for first and last elements
• Adding addFirst(), addLast()
• Removing removeFirst(), removeLast()
• Getting getFirst(), getLast()

Constructors
▪ LinkedList()
• Creates a default empty list
▪ LinkedList(c: Collection<? extends E>)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 17
Initializing a List as We Create it
In Java 9+, all of the following is valid:

A) To create and initialize a specific type of a list (e.g. ArrayList):


ArrayList<Integer> y=new ArrayList<>(Arrays.asList(1,2,3));
ArrayList<Integer> y=new ArrayList<>(List.of(1,2,3));

B) To create a general list (i.e. can only use methods from List):
List<Integer> y = Arrays.asList(1,2,3);//y is modifiable
List<Integer> x = List.of(1,2,3); //x is unmodifiable

Aside: difference between Arrays.asList and List.of:


List.of returns an unmodifiable (immutable) list (Java 9+ only)
Arrays.asList returns a modifiable list
Example: y.set(1,10) is valid (y is modifiable).
x.set(1,10) causes a runtime error (x is immutable)

Note: List.of() is a static (implemented) method in List interface.


COSC 121. Page 18
Example
The code on the right will produces
the same outcome when list is list.add("A");
OUTPUT
declared using any of these two list.add("B"); [X, B, C, D]
2
statements: list.add("C"); -1
false
true
list.set(0, "X"); [X, B, D]
List<String> list = new ArrayList<>(); list.add("D");
System.out.println(list);
OR System.out.println(list.indexOf("C"));
System.out.println(list.indexOf("Z"));
List<String> list = new LinkedList<>(); System.out.println(list.remove("Z"));
System.out.println(list.remove("C"));
System.out.println(list);

COSC 121. Page 19


Practice
Assume list1 = ["red", "yellow", "green"]
list2 = ["red", "yellow", "blue"].
What is list1 after executing each statement in the following code
fragment (as if they were in one program in this order):
a) list1.addAll(list2)?

b) list1.remove(list2)?

c) list1.removeAll(list2)? Q: if we write the statements (a) to (f)


once where list1 & list2 are ArrayLists
d) list1.retainAll(list2)? and once when they are LinkedLists,
will there be any difference in the
e) list1.clear()?
way we write the statements a-f?
f) list1.add(list2)?

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 20
When to use which?
In order to answer this question, we need to learn a few things
first about ArrayLists vs LinkedLists, namely:

1) The internal structure of the two types of lists (ArrayList vs


LinkedList) and they are stored in the memory.

2) How their methods are implemented.


• e.g. while add(E data) is supported by the two lists, this method is
implemented differently in each list.
and the time complexity of the different methods
• In terms of the Big-Oh notation

Next slides, we will discuss each of the above items

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 21
Remember: Structure of an ArrayList
An array list is implemented using an array (a fixed-size data
structure). Whenever the current array cannot hold new elements
in the list, a larger new array is created to replace the current
array. Arrays use an INDEX to reference its elements
memory address
0
1 int[] arr = new int[6];
2
… . arr [index] = arr address + index
arr .
index 0 element 0 arr[0] = arr address Assuming
.
1 element 1 . arr[1] = arr address + 1 1 int = 1
Consecutive
Memory Space … … . memory
. block
Reserved 5 element 5 arr[5] = arr address + 5
.

Illustration:
▪ http://cs.armstrong.edu/liang/animation/web/ArrayList.html
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 22
Basic Structure of a LinkedList, cont.
Each data element is contained in an object, called the node.
When a new element is added to the list, a node is created to
contain it.
Each node is linked to its next neighbor.
A variable head refers to the first node, and a variable tail to the
last node.
▪ If the list is empty, both head and tail are null.
head tail

Element 1 Element 2 Element n

next next … next null

Node 1 Node 2 Node n


COSC 121. Page 23
How LinkedLists are stored in Memory?
0s Used
1 Used
LinkedList list= new LinkedList();
2 Used
. Used // head → null , no space reserved
. Used
head 58 “Joe” list.add("Joe");
Assumption:
. null 1 string =
list.add("Alex");
1 memory block
. Used
. Used
234
234 “Alex”
. null No easy indexing!!
. Used
.

Illustrations:
▪ http://cs.armstrong.edu/liang/animation/web/LinkedList.html
▪ https://visualgo.net/en/list COSC 121. Page 24
Others types of Linked Lists
Circular Linked List

head tail

Element 1 Element 2 Element n

next next … next

Node 1 Node 2 Node n

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 25
Others types of Linked Lists, cont.
Doubly Linked List
▪ This is the type that Java 1.7 uses for LinkedList class
▪ Can be traversed in both directions
head tail

Element 1 Element 2 Element n

null previous previous … previous


next next next null

Node 1 Node 2 Node n

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 26
Others types of Linked Lists, cont.
Circular Doubly Linked List

head tail

Element 1 Element 2 Element n

previous previous … previous


next next next

Node 1 Node 2 Node n

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 27
When to use which (again)?
In general, use either one if you need access through an index.
However, note the following (based on the table on the next slide):
▪ ArrayList:
• Efficient for getting/setting elements by an index
• Good for Inserting/removing elements near end (but not beginning)
• Access elements using “Random Access” (good)
▪ LinkedList:
• Efficient for inserting/removing elements near beginning and end.
• Efficient when using iterators.
• Access elements using “Sequential Access” (bad)
• hence it is not good for getting/setting elements away from beginning/end

When should I use standard arrays?


A list can grow or shrink dynamically. An array is fixed once it is
created. IF your application does not require insertion or deletion of
elements, the most efficient data structure is the array.
COSC 121. Page 28
When to use which?
Methods ArrayList LinkedList
add(e: E) O (1) O (1)
add(index: int, e: E) O (n ) O (n )
remove(e: E) O (n ) O (n )
remove(index: int) O(n) O (n )
get(index: int) O(1) O (n )
set(index: int, e: E) O(1) O(n)
addFirst(e: E) O(n) O(1)
removeFirst() O(n) O (1)
contains(e: E) O (n ) O (n )
indexOf(e: E) O (n ) O (n )
lastIndexOf(e: E) O (n ) O (n )
isEmpty() O (1) O (1)
clear() O (1) O (1)
size() O (1) O (1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 29
get(i) in ArrayList vs LinkedList
Run the code below and compare the time taken by get(i) in ArrayLists vs
LinkedLists
final int N = 100000; long startTime, endTime, totalTime;
//create an ArrayList and a LinkedList of 100,000 elements
ArrayList<Integer> arraylist = new ArrayList<>(N);
for (int i = 0; i < N; i++) arraylist.add(i);
LinkedList<Integer> linkedlist = new LinkedList<Integer>();
for (int i = 0; i < N; i++) linkedlist.add(i);
Exercise: Replace get(i)
//get(i) all elements in ArrayList and compute time
in this code with other
startTime = System.currentTimeMillis();
for (int i = 0; i < N; i++) methods from the table
arraylist.get(i); in previous slide and
endTime = System.currentTimeMillis(); compare the time.
totalTime = endTime - startTime;
System.out.printf("ArrayList: get(i) %d elements took %d ms\n",N,totalTime);

//get(i) all elements in LinkedList and compute time


startTime = System.currentTimeMillis();
for (int i = 0; i <N; i++)
linkedlist.get(i);
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
System.out.printf("LinkedList: get(i) %d elements took %d ms\n",N,totalTime);
COSC 121. Page 30
Big-Oh Notation
Big-Oh notation is a mechanism for quickly communicating
the efficiency of an algorithm.
▪ Big-Oh notation indicates the growth rate of a function
(efficiency) when the size of data (n) changes.
• The letter O is used because the growth rate of a function is also
referred to as the “Order of a function”.

In big-Oh notation:
▪ The performance is specified as a function of n which is the
size of the problem.
• e.g. n may be the size of an array, or the number of values to compute
▪ Only the most significant expression of n is chosen:
• e.g. If the method performs n3 + n2 + n steps, it is O(n3).
• Significance ordering: 2n , n5 , n4 , n3 , n2 , n*log(n) , n , log(n)
▪ Constants are ignored for big-Oh:
• e.g. If the method performs 5*n3 + 4*n2 steps, it is O(n3).
• This is because we measure the growth rate, not the number of
executions, and hence both n and 10n will grow at the same rate.
COSC 121. Page 31
Common Big-Oh Notation Values
There are certain classes of functions with common names:
▪ constant = O(1)
▪ logarithmic = O(log n)
▪ linear = O(n)
▪ quadratic = O(n2)
▪ exponential = O(2n)

These functions are listed in order of fastest to slowest.


▪ For example, for large values of n, an algorithm that is
considered O(n) is much faster than an algorithm that is O(2n).
▪ Big-Oh notation is useful for specifying the growth rate of the
algorithm execution time.
• How much longer does it take the algorithm to run if the input size is
doubled?

COSC 121. Page 32


Big Oh Growth Rates

Big Oh Growth Rates

100
90
80
O(1)
70
60 O(logN)
50 O(N)
40 2
O(N )
30 N
20 O(2 )
10
0

COSC 121. Page 33


Practice: Big-O Notation
What is the Big-O of the following segments of codes?

System.out.print(a[16]);
O(1)
System.out.print(a[n-1]);

for(i = 0; i< n; i++)


O(n)
System.out.print(a[i]);

for(i = 0; i< n; i++)


for(j = 0; j<n; j++) O(n2)
System.out.print(a[i][j]);

COSC 121. Page 34


Demo: ArrayList and LinkedList
The program below creates an integer ArrayList with chosen values. Then it
creates an Object LinkedList from the above ArrayList and insert/remove
elements from the list. Finally, it prints all elements from both lists as in this
sample output:.
Efficiency?!!

Q: Is this the
best way?
Experiment: Printing all elements in reverse order
Experiment (based on the previous slide):
▪ For 100,000 elements, the reported time
• Loop1: 4.212 sec
• Loop2: 0.016 sec

long startTime, endTime;


LinkedList<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 100000; i++) list.add(i);

//Loop 1: using an index


startTime = System.currentTimeMillis();
for (int i = list.size() - 1; i >= 0; i--) list.get(i);
endTime = System.currentTimeMillis();
System.out.printf("Time using index: %d ms\n", (endTime-startTime));

// Loop 2: using an iterator


ListIterator<Integer> itr = list.listIterator();
startTime = System.currentTimeMillis();
while (itr.hasNext()) itr.next();
while (itr.hasPrevious()) itr.previous();
endTime = System.currentTimeMillis();
System.out.printf("Time using iterator: %d ms\n",(endTime-startTime));
COSC 121. Page 40
Practice: ArrayList and LinkedList
Repeat the previous practice question (3 slides ago) but use an iterator to
display the elements of the linked list.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 42

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