# Lecture 02: Lists

## Overview

1. Recap of Last Time
2. The List Abstract Data Type (ADT)
3. List Implementations and Testing

## Last Time

1. Sort a list of numbers
2. Play chess (well)
3. Identify pictures of faces

Tasks 1, 2, and 3 are increasingly more challenging to formalize

## What is a “List”?

• Want to store an ordered collection of items, elements
• E.g., ranked list of courses, to-do list, etc.
• Elements accessed by index

Will’s to-do list:

## What can Lists do?

1. Return element is at index i
2. Insert element at index i
3. Remove element at index i
4. Set value of element at index i

## Formalizing the Specification

The state of a list is a sequence of elements:

• $S = x_0, x_1, x_2, \ldots, x_{n-1}$

• $x_i$ represents the element at index $i$

This is a symbolic representation the state of a List

## Non-Modifying Operations

State $S = x_0, x_1, x_2, \ldots, x_{n-1}$

• size(): return n
• isEmpty(): return n == 0
• get(i): return $x_i$
• exception if i < 0 or i > n-1

State is unchanged after applying these operations

## Modifying Operations

Initial state $S = x_0, x_1, x_2, \ldots, x_{i-1}, x_i, x_{i+1},\ldots, x_{n-1}$

• set(i, y):
• update state to $x_0, x_1, \ldots, x_{i-1}, y, x_{i+1}, \ldots, x_{n-1}$
• update state to $x_0, x_1, \ldots, x_{i-1}, y, x_{i}, x_{i+1}, \ldots, x_{n-1}$
• size is now $n+1$!
• remove(i):
• update state to $x_0, x_1, x_2, \ldots, x_{i-1}, x_{i+1},\ldots, x_{n-1}$
• return value $x_i$

## What Have we Done?

• Specified list operations in a purely formal/symbolic way
• Given any sequence of operations, the correct behavior is completely determined

## Example

Starting from an empty list $S = \varnothing$, perform the following operations:

• remove(2)
• set(2, "green")
• remove(0)

## Specifying an ADT in Java

Java interface allows us to specify required methods

• Does not check what the methods do!

• Audience is a programmer not a computer

See SimpleList.java

# List Implementations

## So Far

• Formal specification of List ADT
• specifies what a List should do
• SimpleList Java interface
• specifies what methods are required to implement list
• comments describe the effects of the methods

Now what?

## How to Implement a List?

How can we represent a List in Java?

• How to store/represent List contents?

## Array-based List Implementation I

Which List operations does an Array support? Which must we implement ourselves?

• size()
• isEmpty()
• get(i)
• set(i, y)
• remove(i)