Linear Data Structures
Lecturer: Nataliia Stulova
Teaching assistant: Mohammadreza Hazirprasand
OF THE UNIVERSITIES OF
BERN, NEUCHÂTEL AND
FRIBOURG
Software Skills Lab
Linear data ● They are abstractions of all
kinds of rows, sequences, and
structures series from the real world...
● … so their elements are
arranged sequentially or
linearly and linked one after
Arrays another in a specified order
Lists
Stacks
Queues
2
Arrays
3
Array data structure
● a native data structure to store a fixed number of elements of the same type
● elements are accessed by their relative position (random access) - each element is independent of
others
array element
N-elements array indices range
from 0 to N-1 h e l l o
0 1 2 3 4
element index
4
Java arrays
On creation arrays of primitive types are filled with
array array
name size default values:
MyType myArray[] = new MyType[size]; boolean status[]; false false
status = new boolean[2]; 0 1
elements type
status[0] = true; true false
MyType myArray[]; 0 1
myArray = new MyType[size];
5
Creating Java arrays
Arrays of primitive types Arrays of objects
int nums[] = new int[2]; Car parking[] = new Car[20];
nums[0] = 23; parking[0] = new Car();
nums[1] = 9; parking[0].setSpeed(0);
int nums[] = {23, 9}; Car truck = new Car();
truck.fuel = 20;
parking[1] = truck;
6
Multi-dimensional arrays
rows columns 0 1 2
Multidimensional arrays are arrays of arrays with each int matrix[][] = new int[2][3]; 0 0 0 0
element of the array holding the reference of other 1 0 0 0
array
0 1 2
MyType matrix[]..[] = new MyType[s1]..[sN]; 0 4 0 0
matrix[0][0] = 4;
matrix[1][2] = 3; 1 0 0 3
number of each dimension
dimensions size
Examples: spreadsheets, games (like sudoku),
timetables, images
7
java.util.Arrays
Reference Javadoc: Arrays (Java SE 11 & JDK 11 )
This class contains various methods for manipulating arrays (such as sorting and searching):
● fill()
● sort() (last lecture)
● binarySearch() (last lecture)
● copyOf()
● equals()
● ...
8
Lists
9
Linked list data structure
● a data structure to store a non-fixed number of elements of the same type
● elements are accessed in their order (sequential access) - each element needs to be connected to
the previous
list element
h e l l o
element link
10
Linked list in Java from scratch
implementing a linked list data structure from public class LinkedList<T> {
scratch in Java can involve Nested Classes - a a //Node inner class
way of logically grouping classes that are only public class Node {
public T data; //Data to store
used in one place public Node nextNode; //Link to next node
}
//head node
h e l l o nu public Node headNode;
ll
...
list head list tail
11
Java lists: Classes VS Interfaces
● List<E> is an Interface - a blueprint of a class, does
interface List<E> { not hold any implementation details
add(...);
remove(...); ● LinkedList<E> is a Class - a blueprint of an object,
... class LinkedList<E> { has attributes and methods, does not hold any values
attributes, if any
} ● myList is an Object - an instance of the
add(...) {...} LinkedList<E> class, holds concrete values in its
remove(...) {...} attributes
...
}
List<String> myList = new LinkedList<String>();
myList.add(“Potatoes”);
12
Accessing list elements
List<String> groceries = Arrays.asList("Potatoes", "Ketchup", "Eggs");
Loops
Iterators new for (int i = 0; i < groceries.size(); i++) {
System.out.println(groceries.get(i));
}
An interface to go through elements in a collection data structure:
○ hasNext() method checks if there are any elements for (String product : groceries) {
System.out.println(product);
remaining in the list
}
○ next() method returns the next element in the iteration
Iterator<String> groceriesIterator = groceries.iterator();
while(groceriesIterator.hasNext()) {
System.out.println(groceriesIterator.next());
}
13
java.util.List
Reference Javadoc: List (Java SE 11 & JDK 11 ) A library interface that provides various useful
operations on lists:
Some classes implementing the List interface:
● get()
LinkedList (Java SE 11 & JDK 11 ) ● add(), addAll()
● remove()
ArrayList (Java SE 11 & JDK 11 ) ● contains(), containsAll()
● clone()
Vector (Java SE 11 & JDK 11 ) ● equals()
● ...
Differences:memory management, element access
(some allow random access), allowing or not null
elements,...
14
Stacks
15
Stack data structure
● a data structure to store a non-fixed number of elements of the same type
● elements are stored sequentially, but accessed by the Last In First Out (LIFO) principle, one at a
time, at the top of the stack
stack element added last
o top of the stack
l
l
e
h bottom of the stack
16
Stack operations
Basic:
● push: add an element to the top of the stack
● pop: remove an element from the top of the stack and
return it
Extra:
- top/peek: get the value of the top element of the stack
without removing the element
- checks for emptiness and fullness
17
Stack implementation and use
Some examples of use Implementations
● an “undo” mechanism in text editors ● array-based, esp. with fixed capacity
● forward and backward navigation in web ● as a resizable array (e.g., using a Vector)
browsers ● linked list-based
● expression parsing and evaluation (e.g., )
● memory management (part II of this course)
18
java.util.Stack<E>
Reference Javadoc: Stack (Java SE 11 & JDK 11 )
The Stack class represents a last-in-first-out (LIFO) stack of objects.
● empty()
● peek()
● pop()
● push(E item)
● search(Object obj)
19
Queues
20
Queue data structure
● a data structure to store a non-fixed number of elements of the same type
● elements are stored sequentially, but accessed by the First In First Out (FIFO) principle, one at a
time, at the top of the stack
queue element added first
h front of the queue
e
l
l
o back of the queue
queue element added last 21
Queue operations
Basic:
● enqueue: add an element to the back of the
queue
● dequeue: remove an element from the front of
the queue and return it
Extra:
- front: get the value of the first element of the
queue without removing the element
- checks for emptiness and fullness
22
Queue implementation and use
Implementations
Some examples of use
● array-based, esp. with fixed capacity
● handling of high-priority processes in an
● linked list-based
operating system is handled using queues
● ordering requests to a printer to print
pages, the requests are handled by using a
queue
● messages on social media, they are sent to a
queue on the server
23
java.util.Queue<E>
Reference Javadoc: Queue (Java SE 11 & JDK 11 )
A library interface that provides various queue operations:
24
What you should remember
Use arrays when: Use lists when:
● you know the number of elements… ● you do not know the number of elements
● … or the number of elements will increase ● you do not need fast access to individual
rarely elements
● you need fast access to individual elements
25
Summary and practice
26
new this keyword: clarify the context
NEW
result[i][j] = this.matrix[i][j] + other.matrix[i][j]
Exercise 1: Arrays
Matrix multiplication I/O
● write a class representing a 2D matrix -
● attributes:
○ int matrix[][] Tests (JUnit, class MatrixTest)
● methods:
○ Matrix(int rows, int cols) - constructor ● dimensions mismatch
○ Matrix add(Matrix other) - addition ● 3 correct cases: 1-column matrix,
○ Matrix product(Matrix other) - multiplication
1-row matrix, a 2x3 matrix
https://en.wikipedia.org/wiki/Matrix_(mathematics)#Basic_operations
27
new static keyword: helper methods (and no objects!)
NEW
Double arMean = Averages.artihMean(ArrayList<E> nums)
NEW
new boxed types: Integer, Float, Double….
Exercise 2: Lists
Computing various average values I/O
● write a class Averages to compute various means: ● Read a sequence of numbers from
arithmetic, geometric, and harmonic System.in
https://en.wikipedia.org/wiki/Average ● Print average values to System.out
● methods:
○ static Double arithMean(ArrayList<E> nums) Tests
○ static Double geomMean(ArrayList<E> nums)
○ static Double harmMean(ArrayList<E> nums)
● one test for each method
28