week 2: review of java arrays sources:

43
Slide 1 Week 2: Review of Java Arrays Sources: Chapter 2 in Supplementary Book (Murach’s Java Programming) Appendix A in Textbook (Carrano): pages A44-A50

Upload: others

Post on 09-Feb-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Week 2: Review of Java Arrays Sources:

Slide 1

Week 2: Review of Java Arrays

Sources:

• Chapter 2 in Supplementary Book (Murach’s Java Programming)

• Appendix A in Textbook (Carrano): pages A44-A50

Page 2: Week 2: Review of Java Arrays Sources:

Slide 2

Outline

• Objectives

• Declaration and Initialization

• array elements

• Processing arrays

• Multi-dimensional arrays

Page 3: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 4

Objectives

Applied

Given a list of values or objects, write code that creates a one-

dimensional array that stores those values or objects.

Use for loops and enhanced for loops to work with the values or

objects in an array.

Use the methods of the Arrays class to fill an array, compare two

arrays, sort an array, or search an array for a value.

Implement the Comparable interface in any class you create.

Create a reference to an array and copy elements from one array

to another.

Page 4: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 5

Objectives (cont.)

Given a table of values or objects, write code that creates a two-

dimensional array that stores those values or objects. The array

can be either rectangular or jagged.

Use for loops and enhanced for loops to work with the values or

objects in a two-dimensional array.

Given the Java code for an application that uses any of the

language elements presented in this chapter, explain what each

statement in the application does.

Knowledge

In general, explain what an array is and how you work with it.

Describe the operation of the enhanced for loop and explain why

it’s especially useful with arrays.

Explain when you need to implement the Comparable interface in

a class you create.

Page 5: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 6

Objectives (cont.)

Explain what happens when you assign a new array to an existing

array variable.

Describe the difference between a rectangular array and a jagged

array, and explain the difference in how you create them.

Page 6: Week 2: Review of Java Arrays Sources:

Slide 7

Outline

• Objectives

• Declaration and Initialization

• Motivation

• Concept of Arrays

• Declaration

• Initialization

• array attributes

• Processing arrays

• Multi-dimensional arrays

Page 7: Week 2: Review of Java Arrays Sources:

Slide 8

Motivation, Concept

• Motivation: • Use cases:

• vectors, matrix algebra, indexed collections, e.g., top-10 list

• Helps implement other collections, e.g., stack, queue, …

• Performance

• Provide fast access to elements given index, e.g., 3rd, 10th, …

• Concept: Arrays is a homogeneous collection

• Positive Example: {“Joe”, “Doug”, “Anne”}

• Positive Example: {2, 4, 6, 8, 10}

• Negative Example: {2, 4, “Joe”, 8}

• Negative Example: { (id = 234), (name = “John Doe”), (age = 42)}

Page 8: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 9

The syntax for declaring and instantiating an array

Two ways to declare an array

type[] arrayName;

type arrayName[];

How to instantiate an array

arrayName = new type[length];

How to declare and instantiate an array in one statement

type[] arrayName = new type[length];

Page 9: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 10

Code that declares an array of doubles double[] prices;

Code that instantiates an array of doubles prices = new double[4];

Code that declares and instantiates an array of

doubles in one statement double[] prices = new double[4];

Page 10: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 11

An array of String objects String[] titles = new String[3];

An array of Product objects Product[] products = new Product[5];

Code that uses a constant to specify the array length final int TITLE_COUNT = 100; // size set at compile time

String[] titles = new String[TITLE_COUNT];

Code that uses a variable to specify the array length Scanner sc = new Scanner(System.in);

int titleCount = sc.nextInt(); // size set at runtime

String[] titles = new String[titleCount];

Page 11: Week 2: Review of Java Arrays Sources:

Slide 12

Outline

• Objectives

• Declaration and Initialization

• Array attributes

• Elements

• length

• Processing arrays

• Multi-dimensional arrays

Page 12: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 13

The syntax for referring to an element of an array arrayName[index] // elements at 0, 1, 2, …, (index – 1)

Code that assigns values to an array of double types double[] prices = new double[4];

prices[0] = 14.95;

prices[1] = 12.95;

prices[2] = 11.95;

prices[3] = 9.95;

//prices[4] = 8.95; // this would throw

// ArrayIndexOutOfBoundsException

Code that assigns values to an array of String types String[] names = new String[3];

names[0] = "Ted Lewis";

names[1] = "Sue Jones";

names[2] = "Ray Thomas";

Code to assign objects to an array of Product objects Product[] products = new Product[2];

products[0] = new Product("java");

products[1] = new Product("jsps");

Page 13: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 14

The syntax for creating an array and assigning values in

one statement type[] arrayName = {value1, value2, value3, ...};

Examples that create an array and assign values in one

statement double[] prices = {14.95, 12.95, 11.95, 9.95};

String[] names = { "Ted Lewis", "Sue Jones", "Ray Thomas"};

Product[] products = {new Product("java"), new Product("jsps")};

Exercise: Which are valid array declarations? (a.) String[] names = new String[5] ;

(b.) String names[] = new String[5] ;

(c.) String[] names = new String[0];

(d.) String[] names = {“one”, “two”};

(e.) All of the above

Page 14: Week 2: Review of Java Arrays Sources:

Slide 15

Outline

• Objectives

• Motivation, Concept, Declaration and Initialization

• array attributes

• Elements

• Length

• Processing arrays

• “for” loop

• java.util.Array Methods: fill, equals, sort, binarySearch, copyOfRange

• Passing array to a function/method

• Multi-dimensional arrays

Page 15: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 16

The syntax for getting the length of an array arrayName.length

Code that puts the numbers 0 through 9 in an array int[] values = new int[10];

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

{

values[i] = i;

}

Q. Which of the following code-segments throw ArrayIndexOutOfBoundsException? int[] values = new int[10];

(a.) values[10] = 10 ;

(b.) values[values.length] = 3;

(c.) for (int i=0; i <= values.length; i++)

{values[i] = i ;}

(d) all of the above

Page 16: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 17

Code that prints an array of prices to the console double[] prices = {14.95, 12.95, 11.95, 9.95};

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

{

System.out.println(prices[i]);

}

The console output

14.95

12.95

11.95

9.95

Page 17: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 18

Code to computes average of an array of prices double sum = 0.0;

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

{

sum += prices[i];

}

double average = sum/prices.length;

Another way to compute the average in a for loop double sum = 0.0;

for (int i = 0; i < prices.length; sum += prices[i++]);

average = sum / prices.length;

Page 18: Week 2: Review of Java Arrays Sources:

Slide 19

Outline

• Objectives

• Motivation, Concept, Declaration and Initialization

• array attributes

• Processing arrays

• “for” loop

• enhanced “for” loop

• java.util.Array Methods: fill, equals, sort, binarySearch, copyOfRange

• Passing array to a function/method

• Multi-dimensional arrays

Page 19: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 20

The syntax of the enhanced for loop for (type variableName : arrayName)

{

statements

}

Code that prints an array of prices to the console double[] prices = {14.95, 12.95, 11.95, 9.95};

for (double price : prices)

{

System.out.println(price);

}

The console output

14.95

12.95

11.95

9.95

Page 20: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 21

Code to compute average of the array of prices double sum = 0.0;

for (double price : prices)

{

sum += price;

}

double average = sum / prices.length;

Compare with traditional “for” loop double sum = 0.0;

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

{

sum += prices[i];

}

double average = sum/prices.length;

Q. Which “for” loop is less likely to throw ArrayIndexOutOfBoundsException? (a.) Enhanced, e.g., for (int v : values ) { s += v ; }

(b.) Traditional, e.g., for (int i=0; i < v.length; i++){s += v[i];}

Q. Which code-fragment be easily rewritten using enhanced “for” loop ? (a.) for (int i=0; i < v.length; i++) {v[i] = i ;}

(b.) for (int i=0; i < v.length; i++) {sum += v[i];}

Page 21: Week 2: Review of Java Arrays Sources:

Slide 22

Outline

• Objectives

• Motivation, Concept, Declaration and Initialization

• array attributes

• Processing arrays

• “for” loop

• enhanced “for” loop

• java.util.Array Methods: fill, equals, sort, binarySearch, copyOfRange

• Passing array to a function/method

• Multi-dimensional arrays

Page 22: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 23

The Arrays class java.util.Arrays

Static methods of the Arrays class fill(arrayName, value)

fill(arrayName, index1, index2, value)

equals(arrayName1, arrayName2)

copyOf(arrayName, length)

copyOfRange(arrayName, index1, index2)

sort(arrayName)

sort(arrayName, index1, index2)

binarySearch(arrayName, value)

Page 23: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 24

Code that uses the fill method int[] quantities = new int[5];

Arrays.fill(quantities, 1); // all elements are set to 1

Code to use the fill method to fill 3 elements in an array int[] quantities = new int[5];

Arrays.fill(quantities, 1, 4, 100); // elements 1, 2, and

// 3 are set to 100

Page 24: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 25

Code that uses the equals method String[] titles1 = { "War and Peace", "Gone With the Wind"};

String[] titles2 = { "War and Peace", "Gone With the Wind"};

if (titles1 == titles2)

System.out.println("titles1 == titles2 is true");

else

System.out.println("titles1 == titles2 is false");

if (Arrays.equals(titles1, titles2))

System.out.println(

"Arrays.equals(titles1, titles2) is true");

else

System.out.println(

"Arrays.equals(titles1, titles2) is false");

The console output

titles1 == titles2 is false

Arrays.equals(titles1, titles2) is true

Page 25: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 26

Code that uses the sort method int[] numbers = {2,6,4,1,8,5,9,3,7,0};

Arrays.sort(numbers);

for (int num : numbers)

{

System.out.print(num + " ");

}

The console output

0 1 2 3 4 5 6 7 8 9

Page 26: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 27

Code that uses the sort and binarySearch methods String[] productCodes = {"mcbl", "jsps", "java"};

Arrays.sort(productCodes);

int index = Arrays.binarySearch(productCodes, "mcbl");

// sets index to 2

Leading Question: Can sort() be used for array of user-defined objects?

Requirement: Its class should implement java.language.Comparable interface

Page 27: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 28

The Comparable interface defined in the Java API public interface Comparable {

int compareTo(Object obj);

}

An Item class that implements the Comparable interface public class Item implements Comparable {

private int number;

private String description;

public Item(int number, String description) {

this.number = number; this.description = description;

}

public int getNumber() { return number;}

public String getDescription() { return description; }

@Override

public int compareTo(Object o) {

Item i = (Item) o;

if (this.getNumber() < i.getNumber()) return -1;

if (this.getNumber() > i.getNumber()) return 1;

return 0;

}

}

Page 28: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 29

Code that sorts an array of Item objects Item[] items = new Item[3];

items[0] = new Item(102, "Duct Tape");

items[1] = new Item(103, "Bailing Wire");

items[2] = new Item(101, "Chewing Gum");

Arrays.sort(items);

for (Item i : items)

System.out.println(i.getNumber() + ": " +

i.getDescription());

The console output

101: Chewing Gum

102: Duct Tape

103: Bailing Wire

Page 29: Week 2: Review of Java Arrays Sources:

Slide 30

Outline

• Objectives

• Motivation, Concept, Declaration and Initialization

• array attributes

• Processing arrays

• “for” loop

• enhanced “for” loop

• java.util.Array Methods: fill, equals, sort, binarySearch, copyOfRange

• Passing array to a function/method

• Multi-dimensional arrays

Page 30: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 31

How to create a reference to an array

Code that creates a reference to an array

double[] grades = {92.3, 88.0, 95.2, 90.5};

double[] percentages = grades;

percentages[1] = 70.2; // changes grades[1] too

System.out.println("grades[1]=" + grades[1]); // prints 70.2

Code that reuses an array variable

double[] grades = new double[5];

grades = new double[20]

Exercise. Which of the following are true after given code-fragment? int[] x = {1, 2, 3};

int[] y = {1, 2, 3};

int[] z = a;

(a.) (x == y)

(b.) Arrays.equals(x, y)

(c.) (x == y)

(d.) Arrays.equals(x, z)

(e.) (y == z)

Page 31: Week 2: Review of Java Arrays Sources:

Slide 32

Passing an array to a function

• Arrays are passed by reference to a function

• Thus, function can change elements of the passed array!

Example: What is the value of x[1] after the following code fragment?

Public static void main( String[] args)

{

int[] x = { 92, 88, 81, 72, 89, 78 } ;

addOnePointEach ( x ) ;

}

Public static void addOnePointEach( int[] y )

{

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

{

y[i] += 1 ;

}

}

Page 32: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 33

How to copy an array with JDK 1.6 or later

Code that copies the values of an array

double[] grades = {92.3, 88.0, 95.2, 90.5};

// Make an independent copy of entire array

double[] percentages = Arrays.copyOf(grades, grades.length);

percentages[1] = 70.2; // doesn't change grades[1]

System.out.println("grades[1]=" + grades[1]); // prints 88.0

Code that copies part of one array into another array

double[] grades = {92.3, 88.0, 95.2, 90.5};

Arrays.sort(grades);

// Copy highest and second highest grades into another array

double[] lowest2Grades = Arrays.copyOfRange(grades, 0, 2);

// Copy second lowest and lowest grades into another array

double[] highest2Grades = Arrays.copyOfRange(grades, 2, 4);

Page 33: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 34

How to copy an array prior to JDK 1.6

The syntax of the arraycopy method of the System class

System.arraycopy(fromArray, intFromIndex, toArray, intToIndex,

intLength);

Code that copies the values of an array

double[] grades = {92.3, 88.0, 95.2, 90.5};

double[] percentages = new double[grades.length];

System.arraycopy( grades, 0, percentages, 0, grades.length);

percentages[1] = 70.2; // doesn't change grades[1]

System.out.println("grades[1]=" + grades[1]); // prints 88.0

How to copy an array prior to JDK 1.6 (cont.)

Code that copies part of one array into another array

double[] grades = {92.3, 88.0, 95.2, 90.5};

Arrays.sort(grades);

double[] lowestGrades = new double[2];

System.arraycopy(grades, 0, lowest2Grades, 0, 2);

double[] highestGrades = new double[2];

System.arraycopy(grades, 2, highest2Grades, 0, 2);

Page 34: Week 2: Review of Java Arrays Sources:

Slide 35

Review Quiz: Basic Arrays

1. What is the value of v[1] after the following code fragment?

int[] v = new int[2]; v[0] = 12; v[1] = 21; v = new int[2];

(a.) 12 (b.) 21 (c.) 0 (d.) none of these.

2. Which of the following gets the number of elements in the array named votes?

(a.) votes.length() (b.) votes.length (c.) votes.size() (d.) Arrays.size(votes)

3. What is the value of x[1] after the following code fragment?

int[] x = new int[2]; x[0] = 12; x[1] = 21; int[] y = x; x[1] = 33;

(a.) 12 (b.) 21 (c.) 33 (d.) none of these.

4. Which of the following performs same task as the given “for” loop:

int[] v = new int[3]; for (int i=0; i < v.length; i++) {v[i] = 2;}

(a.) Arrays.fill(votes, 0, 3, 2) (b.) Arrays.fill(votes, 1, 4, 2) (c.) Arrays.fill(votes, 0, 2, 2)

5. Since Arrays.sort() can sort String objects, what must be true about the String class?

(a.) it has a sort method (b.) it implements comparable interface (c.) it implements comparable method

6. Which of the following code-segments throw ArrayIndexOutOfBoundsException?

int[] v = new int[3];

(a.) v[3] = 3 ; (b.) v[v.length] = 3; (c.) for (int i=0; i <= v.length; i++) {v[i] = i;} (d) all three

7. Which of the following are true after given code-fragment?

int[] x = {1, 2, 3}; int[] y = {1, 2, 3}; int[] z = a;

(a.) (x == y) (b.) Arrays.equals(x, y) (c.) (x == y) (d.) Arrays.equals(x, z) (e.) (y == z)

8. What is the value of “i” after the following code fragment?

int[] x ={3,6,2}; Arrays.sort(x); int i=Arrays.binarySearch(x, 3);

(a.) 0 (b.) 1 (c.) 2 (d.) 3

Page 35: Week 2: Review of Java Arrays Sources:

Slide 36

Outline

• Objectives

• Motivation, Concept, Declaration and Initialization

• array attributes

• Processing arrays

• Multi-dimensional arrays

• Rectangular

• Jagged

Page 36: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 37

The syntax for creating a rectangular array type[][] arrayName = new type[rowCount][columnCount];

A statement that creates a 3x2 array int[][] numbers = new int[3][2];

Code that creates a 3x2 array and initializes it in

one statement int[][] numbers = { {1,2} {3,4} {5,6} };

Page 37: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 38

The syntax for referring to an element of a

rectangular array arrayName[rowIndex][columnIndex]

The indexes for a 3x2 array [0][0] [0][1]

[1][0] [1][1]

[2][0] [2][1]

Code that assigns values to the array numbers[0][0] = 1;

numbers[0][1] = 2;

numbers[1][0] = 3;

numbers[1][1] = 4;

numbers[2][0] = 5;

numbers[2][1] = 6;

Page 38: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 39

Code that processes a rectangular array with

nested for loops int[][] numbers = { {1,2}, {3,4}, {5,6} };

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

{

for (int j = 0; j < numbers[i].length; j++)

System.out.print(numbers[i][j] + " ");

System.out.print("\n");

}

The console output

1 2

3 4

5 6

Page 39: Week 2: Review of Java Arrays Sources:

Slide 40

Outline

• Objectives

• Motivation, Concept, Declaration and Initialization

• array attributes

• Processing arrays

• Multi-dimensional arrays

• Rectangular

• Jagged

Page 40: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 41

The syntax for creating a jagged array type[][] arrayName = new type[rowCount][];

Code that creates a jagged array of integers int[][] numbers = new int[3][];

numbers[0] = new int[10];

numbers[1] = new int[15];

numbers[2] = new int[20];

Code that creates and initializes a jagged array of strings String[][] titles =

{{"War and Peace", "Wuthering Heights", "1984"},

{"Casablanca", "Wizard of Oz", "Star Wars", "Birdy"},

{"Blue Suede Shoes", "Yellow Submarine"}};

Page 41: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 42

Code to create and initialize a jagged array int number = 0;

int[][] pyramid = new int[4][];

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

{

pyramid[i] = new int[i+1];

for (int j = 0; j < pyramid[i].length; j++)

pyramid[i][j] = number++;

}

0

1 2

3 4 5

6 7 8 9

Page 42: Week 2: Review of Java Arrays Sources:

Murach’s Java Programming, C11 © 2011, Mike Murach & Associates, Inc.

Slide 43

Code that uses foreach loops to print a jagged array for (int[] row : pyramid)

{

for (int col : row)

System.out.print(col + " ");

System.out.print("\n");

}

Code to print the contents of the jagged array for (int i = 0; i < pyramid.length; i++)

{

for (int j = 0; j < pyramid[i].length; j++)

System.out.print(pyramid[i][j] + " ");

System.out.print("\n");

}

The console output

0

1 2

3 4 5

6 7 8 9

Page 43: Week 2: Review of Java Arrays Sources:

Slide 44

Review Quiz: Two-dimensional Arrays

1. Which of the following is an invalid two-dimensional array definition?

(a.) int[][] x = new int[2][8] ; (b.) int x[][] = new int[8][];

(c.) int[][] x = new int[][8];

2. What is the value of x[2][1] after following declaration:

int[][] x = { {1, 2}, {3, 4}, { 5, 6}, {7, 8} };

(a.) 1 (b.) 2 (c.) 3 (d.) 4 (e.) 5 (f.) 6 (g.) 7 (h.) 8

3. What is the value of x[1].length after the given code fragment?

int[][] x = new int[4][];

for (int i=0; i < x.length; i++) { x[i] = new int[i+1] ; }

(a.) 1 (b.) 2 (c.) 3 (d.) 4

4. Rewrite the “for” statement in previous question using enhanced “for”.

5. What is the value of x[2][1] after given code fragment:

int[] [] x = new int[5][5];

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

for (int j=0; (j < x[i].length); j++) {x[i][j] = j + i;}

}

(a.) 1 (b.) 2 (c.) 3 (d.) 4

6. What is value of String “s” after execution of following code fragment?

int[][] x = { {6,5}, {4,3}, {1,2} }; String s = “”;

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

{ Arrays.sort(x[i]; s + = x[i][0] + x[i][1]; }

(a.) 123456 (b.) 654321 (c.) 563412 (d.) 214365