Chapter 1: Introduction

Data Structures
Digital dataData typesJava memory model GenericsAbstract data typesChoosing a structureFundamental structures
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Core concepts

Tell a data type, an abstract data type, and a data structure apart.

Choosing a structure

Choose a data structure that fits a problem's requirements.

ADTs in Java

Write an ADT as an interface and a data structure as a class; use references and generics correctly.

Fundamental structures

Know how each fundamental structure organizes data and where it is used.

Digital Data

Digital Data

  • Numbers, text, images, sound: any information stored as 0s and 1s.
  • Examples: text documents, image files, databases, audio recordings.
ADC01011010101101DAC

Analog sound → ADC → 0s and 1s → computer → DAC → analog sound

Digital Data

Why Digital?

Numeric

Everything is stored in binary.

1011 0010
Easy to store

Kept electronically, shared with ease.

disk · cloud · network
Fast to process

Computers work through it at high speed.

~10⁹ operations / second
A computer sees only 0s and 1s. Data structures arrange those bits so they are meaningful and efficient to use.

Digital Data

Representing Digital Data

Text

Character encodings such as ASCII and Unicode.

'A' → 65 → 01000001
Numbers

Integers, floating-point numbers.

13 → 00001101 · 3.14 → IEEE 754
Images

A color value for each pixel.

red pixel → (R, G, B) = (255, 0, 0)
Sound

Digital samples of the sound wave.

CD quality → 44,100 samples per second

Digital Data

Kinds of Digital Data

KindDescriptionExamples
Structuredorganized by a fixed schemarelational database tables, CSV
Semi-structuredpartly organized by tagsXML, JSON
Texttext meant for people to readTXT, email
Images and graphicsvisual dataJPG, PNG
Audio and musicsound recordingsMP3, WAV

Introduction to Data Structures

Data Structures and Algorithms

Algorithm
  • A step-by-step plan for carrying out a task.
  • A cornerstone of computer science.
Data Structure
  • A way of organizing data that fixes how it is stored.
  • The groundwork for managing and processing data efficiently.
  • Good algorithms and data structures make software efficient.
  • Together they solve problems systematically.
Algorithms + Data Structures = Programs
Title of Niklaus Wirth's 1976 book

Introduction to Data Structures

Data Structures

  • A way to organize and store data in a computer.
  • Goal: fast, efficient access to the data.
  • Essential knowledge for any software developer.
  • The right structure makes a program faster and leaner.

Same utensils: jumbled on the left, sorted on the right.
Where would you find what you need faster?

Introduction to Data Structures

Basic Building Blocks

  • Objects group related attributes into one unit with named fields.
  • Arrays store items side by side in consecutive memory slots.
  • Links let items point to one another in any directed pattern.
Objects
Arrays
Links

Introduction to Data Structures

Primitive Data Types

Java typeSizeRange
byte8 bits−128 … 127
short16 bits−32,768 … 32,767
int32 bitsabout ±2.1 billion
long64 bitsabout ±9.2·1018
float32 bitsfloating point (≈7 digits)
double64 bitsfloating point (≈15 digits)
boolean—true / false
char16 bitsUTF-16 code unit
  • Integers, floating-point numbers, booleans, characters.
  • The simplest building blocks.
  • Fixed size in memory.
  • Handled directly by the processor.

Introduction to Data Structures

Data Types

  • Data type: a set of values plus their behavior.
  • Value set: the legal values of the type.
  • Behavior: the operations allowed on those values.
  • Not every operation makes sense for every type.
  • Type safety: types keep errors down; their restrictions tell the programmer what is allowed.
Integers

Addition, subtraction, multiplication, division.

7 / 2 → 3
Strings

Comparison, concatenation, substrings.

"data" + "base"
Invalid operation

The compiler rejects it before the program runs.

"abc" * 2 → compile error

Introduction to Data Structures · The Java memory model

Memory in Java: Stack and Heap

  • A primitive variable holds its value directly.
  • A reference variable holds the address of an object on the heap; new creates the object.
  • Each method call gets a stack frame for its local variables, discarded on return.
  • The garbage collector reclaims unreachable objects; p[0] → NullPointerException.
int x = 5;               // primitive: the value
int[] a = {7, 2, 9};     // reference → array
String s = "data";       // reference → object
int[] p = null;          // refers to nothing
Call stackmain()x5aspnullHeapint[3]729String"data"values / referencesobjects

Introduction to Data Structures · Step through the code

Code Trace: Value or Reference?

main() frameHeapx5y—a—b—

x = 5: a primitive; the value lives in the frame itself.

main() frameHeapx5y5a—b—

y = x: copies the value; x and y are independent.

main() frameHeapx5y7a—b—

y = 7: only y changes; x is still 5.

main() frameHeapx5y7ab—int[3] (object #1)123

The array lives on the heap; a holds only a reference to it (the arrow).

main() frameHeapx5y7abint[3] (object #1)123

b = a: copies the reference, not the array; both arrows point to one object.

main() frameHeapx5y7abint[3] (object #1)923

b[0] = 9: changes the object itself, so a[0] is 9 too (aliasing).

main() frameHeapx5y7abint[3] (object #1)923int[2] (object #2)00

b = new int[2]: b now points to a new, zero-filled array; a is unaffected.

main() frameHeapx5y7abint[3] (object #1)923int[2] (object #2)00

Output: 5 9. Rule: = copies the value of a primitive and the address of a reference.

int x = 5;
int y = x;
y = 7;
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 9;
b = new int[2];
System.out.println(x + " " + a[0]);

Introduction to Data Structures · Java

Generics: One Structure for Every Type

public class Box<T> {
  private T item;
  public void put(T x) { item = x; }
  public T get() { return item; }
}

Box<String> b = new Box<>();
b.put("data");
String s = b.get();     // no cast needed
Box<Integer> m = new Box<>();
m.put(42);              // int → Integer
// m.put("x");          // COMPILE ERROR
Box<T>one template, T = type parameterBox<String>Box<Integer>"data"42accepts only items of type T
  • Types are checked at compile time, so a wrong type never reaches run time.
  • T must be a reference type: no Box<int>; use Integer.
  • Java's collections are generic: ArrayList<E>, Map<K,V>.

Introduction to Data Structures

Non-Primitive Data Structures

More complex structures, such as:

LinearArrays, lists
LinkedLinked lists
HierarchicalTrees
NetworkGraphs
IndexedHash tables
…Sets, maps
  • More complex; can combine several primitive types.
  • Most can grow and shrink (arrays cannot).
  • Built for specialized operations.

Introduction to Data Structures

Data Structures at a Glance

The same four values (7, 2, 9, 5) arranged eight ways, each with its own strengths and weaknesses:

07122935a[2] → 9 (one step)
Arraycontiguous cells, O(1) access by index, fixed size
7295headreach item i: O(n)
Linked listnodes joined by references, flexible size
7295top →pushpop
StackLIFO: push and pop at the top only
7295frontrearout at front · in at rear
QueueFIFO: first in, first out
7295root
Treehierarchy: root, children, leaves
7295
Graphnodes + edges, many-to-many
051272349k mod 5
Hash tableh(k) picks the bucket; O(1) on average
7295{7, 2, 9, 5} ∪ {7} = same
Set / Mapunique elements / key → value

Introduction to Data Structures

Abstract Data Types vs. Data Structures

Abstract Data Type (ADT)
  • Lists, stacks, queues, sets, maps, graphs…
  • Defines which operations exist (the behavior).
  • Ignores implementation details.
Data Structure
  • Linked lists, arrays, adjacency matrices…
  • Concrete structures that implement ADTs.
  • Focus on memory and performance details.
List ADT add · remove · get(i) · size Array Linked list

Introduction to Data Structures

From ADT to Java: The interface

public interface Stack<E> {
  int size();         // number of elements
  boolean isEmpty();  // is it empty?
  void push(E e);     // add on top
  E top();            // return the top element
  E pop();            // remove and return the top
}
  • interface = the ADT's contract: what it does.
  • class = the data structure: how it does it.
  • One ADT, many possible implementations.
Client codes.push(5); s.pop();knows only the operations«interface» Stack<E>size · isEmpty · pushtop · popimplementsArrayStack<E>array + index tLinkedStack<E>linked nodes
Stack<Integer> s = new ArrayStack<>(10); — to swap implementations, change only this line; client code stays the same.

Introduction to Data Structures · From ADT to data structure

One Implementation: ArrayStack

public class ArrayStack<E> implements Stack<E> {
  private E[] data;         // the elements
  private int t = -1;       // index of the top element
  public ArrayStack(int capacity) {
    data = (E[]) new Object[capacity];
  }
  public int size() { return t + 1; }
  public boolean isEmpty() { return t == -1; }
  public E top() {
    if (isEmpty()) return null;
    return data[t];
  }
  // push and pop
}
05182null3null▲ t = 1size() = t + 1 = 2
OperationTime
size, isEmpty, topO(1)
push, popO(1)
MemoryO(N) (capacity)
  • Java can't create a generic array directly, hence (E[]) new Object[..].
  • Fixed capacity: push throws once the array is full.

Introduction to Data Structures · Step through the code

Code Trace: push / pop

0null1null2null3nullt = −1 (empty)

s is an empty ArrayStack with capacity 4 (t = −1). Call push(5).

0null1null2null3nullt = −1 (empty)

size() = 0 ≠ 4 → not full.

051null2null3null▲ t

++t → t = 0, then data[0] = 5. Increment first, then write.

051null2null3null▲ t

Call push(8).

051null2null3null▲ t

size() = 1 ≠ 4 → not full.

05182null3null▲ t

++t → t = 1, then data[1] = 8. Increment first, then write.

05182null3null▲ t

Call pop(); the result will be printed.

05182null3null▲ t

t = 1 → not empty; go on.

05182null3null▲ te8

e = data[1] = 8: the most recently added element (LIFO).

051null2null3null▲ te8

Clear the cell to null so the object can be collected; t-- → t = 0.

051null2null3null▲ te8

return 8: the call's frame is removed.

051null2null3null▲ t

8 is printed.

051null2null3null▲ t

push(3): cell 1, now free, gets reused.

051null2null3null▲ t

size() = 1 ≠ 4 → not full.

05132null3null▲ t

++t → t = 1, then data[1] = 3. Increment first, then write.

05132null3null▲ t

Final state: [5, 3], t = 1. Each operation takes a fixed number of steps, whatever n is → O(1).

public void push(E e) {
  if (size() == data.length)
    throw new IllegalStateException("full");
  data[++t] = e;
}
public E pop() {
  if (isEmpty()) return null;
  E e = data[t];
  data[t--] = null;     // let GC reclaim it
  return e;
}
s.push(5); s.push(8);
System.out.println(s.pop());
s.push(3);

Introduction to Data Structures

Organizing Data

Unordered
Linear
Tree
Graph
ArrangementRelationshipEveryday example
Unorderednonestudents in a classroom
Linearone-to-onestudents waiting in line
Treeone-to-manya family tree
Graphmany-to-manya road map

Introduction to Data Structures

Choosing a Data Structure

A few questions drive the choice:

  • Can the structure be filled all at once, up front?
  • Will elements be deleted?
  • Does insertion order matter?
  • Can the elements be sorted?
  • Are elements processed in a fixed order, or is random access needed?
Contents won't change? Use a static structure. Frequent insertions and deletions? Use a dynamic one.
Fast access by index (position)?yesArraynoInsert/delete often at front/middle?yesLinked listnoLast in, first out?yesStacknoFirst in, first out?yesQueuenoLookup by key, or uniqueness?yesMap / SetnoHierarchy or network relations?yesTree / Graph

Fundamental Data Structures

Fundamental Data Structures: An Overview

StructureKey ideaTypical uses
Arraycontiguous cells; O(1) access by index, fixed sizetables, matrices; the base of other structures
Linked listnodes joined by references; flexible sizefrequent insertion and deletion
StackLIFO: add / remove only at the topundo, the call stack, bracket matching
QueueFIFO: add at the rear, remove at the frontprint queue, task queue, BFS
Treehierarchy: root, children, leavesfile systems, HTML (DOM), indexes
Priority queuehighest priority always first (heap)task scheduling, emergency-room triage
Map / hash tablekey → value; h(k) picks the bucket, O(1) on averagestudent ID → record, caches, word counts
Setdistinct elements; fast membership testsremoving duplicates, union and intersection
Graphnodes + edges; many-to-many relationsroad maps, social networks, shortest paths

Summary

Summary

TopicKey points
Digital datatext, numbers, images, and sound all become 0s and 1s, each under its own encoding
Data typea value set plus operations; type safety catches errors at compile time
Primitive / referencea primitive holds its value; a reference points to a heap object, and assignment copies only the reference
GenericsBox<T>: one class for every reference type; Integer, not int
ADT / data structurethe ADT says what (interface); the data structure says how (class)
Choosing a structuredepends on the access pattern, how often we insert / delete, ordering needs, and the kind of relationship

Summary

Sample Problems

  1. Which data structure fits "undo" in a text editor? Why?
  2. Which structure lets a printer print documents in the order they arrive?
  3. Which structure gives fast lookup of a student's record by student ID?
  4. How would you model a city map to find the shortest route between two points?
  5. Which structure would you use to remove duplicates from a list?
  6. In Java, is the stack ADT written as an interface or a class? Which is ArrayStack?
Show answers
  1. A stack (LIFO): the most recent action is undone first.
  2. A queue (FIFO).
  3. A map / hash table (key: student ID).
  4. A weighted graph: intersections as nodes, roads as edges, distances as weights.
  5. A set.
  6. The ADT is an interface (Stack<E>): it says what to do. ArrayStack is a class that implements it, so it is a data structure.

Summary

Exercises

  1. After int[] a = {1, 2}; int[] b = a; b[1] = 7;, what is a[1]? Why?
  2. Why doesn't Box<int> b; compile? What should you write instead?
  3. Write the character 'B' and the number 13 as 8-bit patterns.
  4. After String s = "data"; String t = s; t = t + "!";, what is s? Why?
  5. Starting from an empty ArrayStack with capacity 3, run push(1), push(2), pop(), push(3), push(4). What are t and the array at the end?
  6. A music player needs a playlist in order, a "recently played" list, and fast search by song title. Which structures fit?
Answers / hints
  1. 7: b = a copies the reference, so both variables point to the same array.
  2. T must be a reference type: write Box<Integer> (autoboxing).
  3. 'B' = 66 = 01000010; 13 = 00001101.
  4. "data": strings are immutable; t + "!" creates a new object, and only t points to it.
  5. t = 2, array [1, 3, 4]: pop returns 2, and 3 takes its place.
  6. A list (play order), a stack (most recently played on top), a map (title → song).

Summary

Further Reading

  • Goodrich, Tamassia, and Goldwasser, Data Structures and Algorithms in Java, 6th ed., 2014.
  • Wirth, Algorithms + Data Structures = Programs, 1976.
  • Oracle, Java SE 17 API documentation.

The End

Chapter 1: Introduction
Next deck: Chapter 2: Algorithm Analysis · Study questions · Glossary
1 / 1 Sercan KÜLCÜ. All rights reserved.