Chapter 1: Introduction
Introduction
Learning Outcomes
Tell a data type, an abstract data type, and a data structure apart.
Choose a data structure that fits a problem's requirements.
Write an ADT as an interface and a data structure as a class; use references and generics correctly.
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.
Analog sound → ADC → 0s and 1s → computer → DAC → analog sound
Digital Data
Why Digital?
Everything is stored in binary.
1011 0010Kept electronically, shared with ease.
disk · cloud · networkComputers work through it at high speed.
~10⁹ operations / secondDigital Data
Representing Digital Data
Character encodings such as ASCII and Unicode.
'A' → 65 → 01000001Integers, floating-point numbers.
13 → 00001101 · 3.14 → IEEE 754A color value for each pixel.
red pixel → (R, G, B) = (255, 0, 0)Digital samples of the sound wave.
CD quality → 44,100 samples per secondDigital Data
Kinds of Digital Data
| Kind | Description | Examples |
|---|---|---|
| Structured | organized by a fixed schema | relational database tables, CSV |
| Semi-structured | partly organized by tags | XML, JSON |
| Text | text meant for people to read | TXT, email |
| Images and graphics | visual data | JPG, PNG |
| Audio and music | sound recordings | MP3, WAV |
Introduction to Data Structures
Data Structures and Algorithms
- A step-by-step plan for carrying out a task.
- A cornerstone of computer science.
- 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.
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.
Introduction to Data Structures
Primitive Data Types
| Java type | Size | Range |
|---|---|---|
byte | 8 bits | −128 … 127 |
short | 16 bits | −32,768 … 32,767 |
int | 32 bits | about ±2.1 billion |
long | 64 bits | about ±9.2·1018 |
float | 32 bits | floating point (≈7 digits) |
double | 64 bits | floating point (≈15 digits) |
boolean | — | true / false |
char | 16 bits | UTF-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.
Addition, subtraction, multiplication, division.
7 / 2 → 3Comparison, concatenation, substrings.
"data" + "base"The compiler rejects it before the program runs.
"abc" * 2 → compile errorIntroduction 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;
newcreates 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
Introduction to Data Structures · Step through the code
Code Trace: Value or Reference?
x = 5: a primitive; the value lives in the frame itself.
y = x: copies the value; x and y are independent.
y = 7: only y changes; x is still 5.
The array lives on the heap; a holds only a reference to it (the arrow).
b = a: copies the reference, not the array; both arrows point to one object.
b[0] = 9: changes the object itself, so a[0] is 9 too (aliasing).
b = new int[2]: b now points to a new, zero-filled array; a is unaffected.
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
- Types are checked at compile time, so a wrong type never reaches run time.
- T must be a reference type: no
Box<int>; useInteger. - Java's collections are generic:
ArrayList<E>,Map<K,V>.
Introduction to Data Structures
Non-Primitive Data Structures
More complex structures, such as:
- 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:
Introduction to Data Structures
Abstract Data Types vs. Data Structures
- Lists, stacks, queues, sets, maps, graphs…
- Defines which operations exist (the behavior).
- Ignores implementation details.
- Linked lists, arrays, adjacency matrices…
- Concrete structures that implement ADTs.
- Focus on memory and performance details.
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.
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 }
| Operation | Time |
|---|---|
| size, isEmpty, top | O(1) |
| push, pop | O(1) |
| Memory | O(N) (capacity) |
- Java can't create a generic array directly, hence
(E[]) new Object[..]. - Fixed capacity:
pushthrows once the array is full.
Introduction to Data Structures · Step through the code
Code Trace: push / pop
s is an empty ArrayStack with capacity 4 (t = −1). Call push(5).
size() = 0 ≠ 4 → not full.
++t → t = 0, then data[0] = 5. Increment first, then write.
Call push(8).
size() = 1 ≠ 4 → not full.
++t → t = 1, then data[1] = 8. Increment first, then write.
Call pop(); the result will be printed.
t = 1 → not empty; go on.
e = data[1] = 8: the most recently added element (LIFO).
Clear the cell to null so the object can be collected; t-- → t = 0.
return 8: the call's frame is removed.
8 is printed.
push(3): cell 1, now free, gets reused.
size() = 1 ≠ 4 → not full.
++t → t = 1, then data[1] = 3. Increment first, then write.
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
| Arrangement | Relationship | Everyday example |
|---|---|---|
| Unordered | none | students in a classroom |
| Linear | one-to-one | students waiting in line |
| Tree | one-to-many | a family tree |
| Graph | many-to-many | a 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?
Fundamental Data Structures
Fundamental Data Structures: An Overview
| Structure | Key idea | Typical uses |
|---|---|---|
| Array | contiguous cells; O(1) access by index, fixed size | tables, matrices; the base of other structures |
| Linked list | nodes joined by references; flexible size | frequent insertion and deletion |
| Stack | LIFO: add / remove only at the top | undo, the call stack, bracket matching |
| Queue | FIFO: add at the rear, remove at the front | print queue, task queue, BFS |
| Tree | hierarchy: root, children, leaves | file systems, HTML (DOM), indexes |
| Priority queue | highest priority always first (heap) | task scheduling, emergency-room triage |
| Map / hash table | key → value; h(k) picks the bucket, O(1) on average | student ID → record, caches, word counts |
| Set | distinct elements; fast membership tests | removing duplicates, union and intersection |
| Graph | nodes + edges; many-to-many relations | road maps, social networks, shortest paths |
Summary
Summary
| Topic | Key points |
|---|---|
| Digital data | text, numbers, images, and sound all become 0s and 1s, each under its own encoding |
| Data type | a value set plus operations; type safety catches errors at compile time |
| Primitive / reference | a primitive holds its value; a reference points to a heap object, and assignment copies only the reference |
| Generics | Box<T>: one class for every reference type; Integer, not int |
| ADT / data structure | the ADT says what (interface); the data structure says how (class) |
| Choosing a structure | depends on the access pattern, how often we insert / delete, ordering needs, and the kind of relationship |
Summary
Sample Problems
- Which data structure fits "undo" in a text editor? Why?
- Which structure lets a printer print documents in the order they arrive?
- Which structure gives fast lookup of a student's record by student ID?
- How would you model a city map to find the shortest route between two points?
- Which structure would you use to remove duplicates from a list?
- In Java, is the stack ADT written as an interface or a class? Which is
ArrayStack?
Show answers
- A stack (LIFO): the most recent action is undone first.
- A queue (FIFO).
- A map / hash table (key: student ID).
- A weighted graph: intersections as nodes, roads as edges, distances as weights.
- A set.
- The ADT is an interface (
Stack<E>): it says what to do.ArrayStackis a class that implements it, so it is a data structure.
Summary
Exercises
- After
int[] a = {1, 2}; int[] b = a; b[1] = 7;, what isa[1]? Why? - Why doesn't
Box<int> b;compile? What should you write instead? - Write the character
'B'and the number 13 as 8-bit patterns. - After
String s = "data"; String t = s; t = t + "!";, what iss? Why? - Starting from an empty
ArrayStackwith capacity 3, run push(1), push(2), pop(), push(3), push(4). What are t and the array at the end? - A music player needs a playlist in order, a "recently played" list, and fast search by song title. Which structures fit?
Answers / hints
- 7:
b = acopies the reference, so both variables point to the same array. - T must be a reference type: write
Box<Integer>(autoboxing). - 'B' = 66 =
01000010; 13 =00001101. "data": strings are immutable;t + "!"creates a new object, and only t points to it.- t = 2, array [1, 3, 4]: pop returns 2, and 3 takes its place.
- 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.