Computer Science 101

Data Abstraction

Gregory M. Kapfhammer


flickr photo by "Cowboy" Ben Alman shared under a Creative Commons (BY-NC-ND) license

Color Scheme

Key Concept

Corresponding Diagram

In-Class Discussion

In-Class Activity

Details in the Textbook

What is an Array?

Motivation for Using Arrays

Important Details

An array stores a list of values

The number corresponding to each position is the index

An array of size N is indexed from 0 to N-1

Why do we start the index at the value of 0?

Array Bounds Checking

Ensures that the index is within the array

Why is this important to perform?

Let's avoid buffer overflow attacks!

Also, enables the detection of program defects

Can this be fully done at compile time?

What are the associated overheads?

Array Details

How do we declare an array?

int[] grades; and int grades[]; are both acceptable

Be consistent when you are implementing your programs!

What is the "Google Standard" for this?

How do we initialize an array to specific values?

int[] scores = {87, 98, 60, 80};

Arrays as Parameters

What method always accepts an array as a parameter?

An array as a parameter can be modified

You can change the contents of the array

You cannot make the array refer to another array

Command-Line Arguments

Are there other ways to give a program input?

Yes! You can input command-line arguments.

Did you ever notice that main has a parameter?

What is the purpose of String[] args?

TicTacToe

What is the meaning of? ...

private int board[][] = new int[3][3];

board[0][0] + board[0][1] + board[0][2]

String[] outcome = {"O wins", "Tie", "X wins"};

What is the output of this program?

CaesarCipher

What is the purpose of this class?

What is the meaning of? ...

protected char[] encoder = new char[26];

encoder[k] = (char) ('A' + (k + rotation) % 26

for (int k=0; < msg.length; k++)

if (Character.isUpperCase(msg[k]))

msg[k] = code[j];

What is the output of this program?

Sorting

Insertion Sort

Inputs and outputs

Inputs and outputs

Consider each element

Find element's proper location

Shift data values either left or right

All operations performed on an array!

Any questions about arrays?

Cloning data structures

No "one size fits all" answer

clone method

System.arraycopy method

Shallow copy of an array

Deep copy of an array

Assignment with arrays in Figure 3.23

Using clone in Figure 3.24

Primitives versus references

Using clone in Figure 3.25

What is the problem with this approach?

How do you perform a deep copy?

Questions about cloning a data structure?