Docsity

Java Arrays: Anatomy, Properties, and Manipulation, Study notes of Computer Science

Toggle sidebar
bg1
1
CS111 Computer Programming
Department of Computer Science
Wellesley College
Arrays
Friday, November 9, 2007
Arrays 17-2
Arrays: Motivation
oLists are great for representing a collection of values, but can
only access elements in order from front to back.
oWe often want an indexed collection where we can directly
access an element at
any
index. Many languages (including Java)
provide
arrays
for this purpose.
oAn array is an indexed collection of variables, which we will call
the slots of the array. The values in the slots are the elements
of the array.
0 1 2
String []
words
“I” “am” “Sam”
ExecutionLand ObjectLand
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Java Arrays: Anatomy, Properties, and Manipulation and more Study notes Computer Science in PDF only on Docsity!

CS111 Computer Programming

Department of Computer Science Wellesley College

Arrays

Friday, November 9, 2007 Arrays 17- 2

Arrays: Motivation

o Lists are great for representing a collection of values, but can

only access elements in order from front to back.

o We often want an indexed collection where we can directly

access an element at any index. Many languages (including Java)

provide arrays for this purpose.

o An array is an indexed collection of variables, which we will call

the slots of the array. The values in the slots are the elements

of the array.

0 1 2 String [] words “I” “am” “Sam” ExecutionLand (^) ObjectLand

Arrays 17- 3 Anatomy of an Array Diagram 0 1 2 String [] “I” “am” “Sam” ObjectLand an array object slot indices elements slots (variables) the type of the array object (T [ ] is pronounced “array of T” ) Arrays 17- 4 Arrays Are Homogeneous Collections 0 false boolean [] tests 1 false 2 false 3 true 0 4 1 7 3 8 2 3 4 6 int [] nums 0 1 Location [] line x y Location x y Location 5 2

  • 4

All the elements of a Java* array

must have the same type.

0 1 2 String [] words “I” “am” “Sam”

  • We’ll only talk about Java arrays in this lecture. Array details can differ from language to language.

Arrays 17- 7 Array Indexing

If a denotes an array and i denotes

an integer, the notation a[i]

(pronounced “a sub i”)

refers to the ith slot of a.

In most contexts, a[i] evaluates to

the contents of the slot:

words[1] // evaluates to “am”

nums[4] // evaluates to 6

tests[1+2] // evaluates to true

line[0].x // evaluates to 5

0 false boolean [] tests 1 false 2 false 3 true 0 4 1 7 3 8 2 3 4 6 int [] nums 0 1 Location [] line x y Location x y Location 5 2

  • 4 0 1 2 String [] words “I” “am” “Sam” Arrays 17- 8 ArrayIndexOutOfBoundsException

An ArrayIndexOutOfBoundsException occurs when an

invalid index is used.

Examples:

words[-1]

words[4]

words[3] (gotcha!)

words[words.length] (gotcha!)

0 1 2 String [] words “I” “am” “Sam”

Arrays 17- 9 Array Slots are Mutable

The assignment a[i] = val changes the

contents of the ith slot of a to val.

0 4 1 7 3 8 2 3 4 6 int [] nums 0 17 1 7 3 8 2 3 4 6 int [] nums 0 17 1 11 3 8 2 3 4 6 int [] nums 0 17 1 11 3 8 2 3 4 7 int [] nums nums[0] = 17; nums[1] = nums[2] + nums[3]; nums[4]++; // means nums[4] = nums[4] + 1; Arrays 17- 10 Swapping Array Elements 0 1 2 String []

words

“I” “am” “Sam” 0 1 2 String []

words

“Sam”“am” “I” 0 1 2 String []

words

“Sam” “I” “am” swap(words,0,2); swap(words,1,2); public static void swap (String [] strings, int i, int j) { }

Arrays 17- 13 Array Elements can be Any Type

String [] words =

new String [] {“I”, “am”, “Sam”};

boolean [] tests =

new boolean []

{false, false, false, true};

Location [] line =

new Location []

{new Location(5,2),

new Location(-3,4)};

0 false boolean [] tests 1 false 2 false 3 true 0 1 Location [] line x y Location x y Location 5 2

  • 4 0 1 2 String [] words “I” “am” “Sam” Arrays 17- 14 Pop Quiz! What Does This Code Print?

Buggle [] bugs = new Buggle [] {new Buggle(), new Buggle()};

bugs[0].forward(3);

bugs[1].left();

Buggle becky = new Buggle();

becky.setPosition(bugs[0].getPosition());

becky.setHeading(bugs[1].getHeading());

bugs[0] = becky;

bugs[1] = bugs[0];

bugs[0].forward(2);

System.out.println(bugs[1].getPosition());

Arrays 17- 15 Null Pointers 0 1 2 String [] words “I” “am” The default array value for Objects is null (the null pointer), which represents “no object”. String [] words2 = new String [3]; 0 1 2 String [] words words2[0] = “I”; words2[1] = “am”; words2[0] == null // evaluates to false words2[2] == null // evaluates to true; We depict variables holding the null pointer value as a box with a slash. Arrays 17- 16 NullPointerException Any attempt to send a message to the null pointer value results in a NullPointerException. words2[1].length() // evaluates to 2 // (length of string “am”, not of array) words2[2].length() // generates a NullPointerException NullPointerExceptions due to uninitialized variables are extremely common and will haunt you from now on. 0 1 2 String [] words “I” “am”

Arrays 17- 19 split() The split() instance method of the String class is useful for creating string arrays: String [ ] seuss = “I do not like green eggs and ham”.split(“ ”); StringArray.toString(seuss) // evaluates to “{I,do,not,like,green,eggs,and,ham}” Arrays 17- 20 Summing an Array 0 4 1 7 3 8 2 3 4 6 int[] nums // Assume this is in the class IntArray public static int sum (int [ ] a) { } Want IntArray.sum(nums) → 28 5 28

i result

Iteration Table

Arrays 17- 21 Testing sum()

IntArray.sum(new int [] {4,7,3,8,6}) 28 Can test interactively in the Dr. Java Interaction Pane: Can include hardwired test arrays in a main() method: public static void main (String [] args) { String [ ] test = new int [ ] {4,7,3,8,6}; System.out.println(“sum(” + IntArray.toString(test)+ “) = ” + sum(test)); } Can read test arrays from the command line: public static void main (String [] args) { String [ ] test = new int [args.length]; for (int i = 0; i < args.length; i++) { test[i] = Integer.parseInt(args[i]); } System.out.println(“sum(” + IntArray.toString(test) + “) = ” + sum(test)); } Arrays 17- 22 Summing from Top Down 0 4 1 7 3 8 2 3 4 6 int[] nums // Assume this is in the class IntArray public static int sum (int [ ] a) { } Want IntArray.sum(nums) → 28 -1 28

i result

Iteration Table

Arrays 17- 25 Nondestructive (Copying) Mapper 0 4 1 7 3 8 2 3 4 6 int[] nums // Assume this is in the class IntArray public static int[] mapDoubleCopy (int [] a) { }

int[] c = IntArray.mapDoubleCopy(nums);

Before:

0 4 1 7 3 8 2 3 4 6 int[] nums

After: int[]

c

0 8 1 14 3 16 2 6 4 12 Arrays 17- 26 Destructive Array Reversal 0 4 1 7 3 8 2 3 4 6 int[] nums // Assume this is in the class IntArray public static void reverse (int [] a) { }

IntArray.reverse(nums);

Before:

0 6 1 8 3 7 2 3 4 4 int[]

After: nums

Arrays 17- 27 A Broken Array Reversal

// Assume this is in the class IntArray

public static void reverse (int [] a) {

for (int i = 0; i < a.length; i++) {

IntArray.swap(a, i, a.length – 1 - i);

The following destructive reverse method attempts to

reverse an array using swap(). Unfortunately, it has a bug.

Please fix the method so that it works.

Arrays 17- 28 Nondestructive Array Reversal 0 4 1 7 3 8 2 3 4 6 int[] nums // Assume this is in the class IntArray public static int[] reverseCopy (int [] a) { }

int[] c = IntArray.reverseCopy(nums);

Before:

0 4 1 7 3 8 2 3 4 6 int[] nums

After:

0 6 1 8 3 7 2 3 4 4 int[] c

Arrays 17- 31

Good news & bad news

Lists Arrays

Find first element

Find last element

Add element to front

Add element to end

Find length

Mutable

Work for diff types

0 4 1 7 3 8 2 3 4 6 int[] array

list1 4 7 3 8 6 Ø

Arrays 17- 32

Java Arrays: Summary of Properties

o Arrays are fixed-length indexed collections of elements.

Once created, the size of an array cannot change.

o Elements are 0-indexed (i.e., indices start at 0, not 1).

o Every element can be accessed cheaply , independent of

index.

o Arrays are homogeneous collections: all elements must have

the same type.

o There is a special concise syntax for creating, accessing

and updating arrays.

o Dynamic (run-time) index checking ensures that indices of

all array operations are valid.

o Arrays are objects that are not instances of any class.

o Arrays are the answer to the following analogy question:

Recursion : lists :: iteration : ???