1 chapter 10 – arrays and arraylist s array basics array declaration array creation array element...

80
1 Chapter 10 – Arrays and ArrayLists Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property Partially Filled Arrays Copying an Array Histograms Searching an Array Sorting an Array 1 2

Upload: eric-small

Post on 04-Jan-2016

255 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

1Chapter 10 – Arrays and ArrayLists

Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property Partially Filled Arrays Copying an Array Histograms Searching an Array Sorting an Array

1

2

Page 2: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

2Chapter 10 – Arrays and ArrayLists

Selection Sort Two-Dimensional Arrays Arrays of Objects The ArrayList Class

How to Create an ArrayList Object Adding Elements to an ArrayList Object How to Access an Element Within an ArrayList How to Update an ArrayList Object Additional ArrayList Methods Printing or Concatenating an ArrayList

Storing Primitives in an ArrayList ArrayList Example Using Anonymous Objects

and the For-Each Loop ArrayList Objects Versus Standard Arrays

Page 3: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

3

Array Basics

A class stores a group of related data, and it stores the methods that operate on that data.

An array is a limited version of a class. Like a class, an array also stores a group of related data, but an array does

not store methods. Another difference between an array and a class is that an array's data must

all be of the same type. Here's a picture of an array that holds a list of speed-dial phone

numbers. Each of the five boxes is called an array element and each box stores one phone number.

phoneList

8167412000

2024561111

7852963232

8008675309

0035318842133

first speed-dial phone number

last speed-dial phone number

Page 4: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

4

Array Basics

A class uses dot notation to access one of its members. On the other hand, an array uses square brackets around an

index to access one of its elements. The rightmost column shows how to access each of the 5

elements in the phoneList array. Note that the index values start at 0 instead of 1 and the last

index value is one less than the number of elements in the array.

1

2

index phoneList

how to access each

element

0 8167412000 phoneList[0]

1 2024561111 phoneList[1]

2 7852963232 phoneList[2]

3 8008675309 phoneList[3]

4 0035318842133

phoneList[4]

5 elements

Page 5: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

5

Array Basics

Here's how you can change the first phone number to 2013434:phoneList[0] = 2013434;

And here's how you can print the second phone number:System.out.println(phoneList[1]);

2

1

Page 6: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

6

Array Basics

/************************************************************** SpeedDialList.java* Dean & Dean** This program creates a cell phone speed-dial phone number* list and prints the created list.*************************************************************/

import java.util.Scanner;

public class SpeedDialList{ public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); long[] phoneList; // list of phone numbers int sizeOfList; // number of phone numbers long phoneNum; // an entered phone number

System.out.print( "How many speed-dial numbers would you like to enter? "); sizeOfList = stdIn.nextInt(); phoneList = new long[sizeOfList];

1

2

3

Page 7: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

7

Array Basics

for (int i=0; i<sizeOfList; i++) { System.out.print("Enter phone number: "); phoneNum = stdIn.nextLong(); phoneList[i] = phoneNum; } // end for

System.out.println("\nSpeed Dial List:"); for (int i=0; i<sizeOfList; i++) { System.out.println((i + 1) + ". " + phoneList[i]); } // end for } // end main} // end class SpeedDialList

1

2

3

4

5

Page 8: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

9

Array Declaration

An array is a variable and, as such, it must be declared before you can use it.

Array declaration syntax:<element-type>[] <array-variable>;

Array declaration examples:int[] ids;

double[] workHours;

String[] names;

1

2

Page 9: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

10

Array Creation

In Java, arrays are objects. As with all objects, arrays are

created/instantiated with the new operator. Syntax for creating and assigning an array

object:<array-variable> = new <element-type>[<array-size>];

Example:long[] phoneList;

phoneList = new long[10];

1

2

3

<element-type> indicates the type of each element in the array

<array-size> indicates the number of elements in the array

array creation4

Page 10: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

11

Array Creation

It's legal to combine an array's declaration, creation, and assignment operations. Here's an example:long[] phoneList = new long[10];

Provide a single statement that declares, creates, and assigns a 100-element array that stores book titles.

1

2

Page 11: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

12

Array Element Initialization

An array initializer is a single statement made up of an array declaration, creation, and {} assignment.

Array element initialization syntax:<element-type>[] <array-name> = {<element-values-list>};

Array element initialization example:String[] students = {"Christopher", "TJ", "Ellie"};

When an array initializer is used, the size of the array equals the number of elements in the initialization list.

Note that with an array initializer, you creating an array object without using the new operator.

1

Page 12: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

13

Array Default Values

An array is an object and an array's elements are the instance variables for an array object. As such, an array's elements get default values when the array is instantiated, the same as any other instance variables get default values.

Here are the default values for array elements (they're also the default values for all instance variables):

2

1

Array element's type Default value

integer 0

floating point 0.0

boolean false

reference null

Page 13: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

14

Array length Property

Suppose you have a five-element colors array that's been initialized like this: String[] colors = {"blue", "gray", "lime", "teal", "yellow"};

Here's how to print such an array:for (int i=0; i<colors.length; i++){ System.out.println(colors[i]);}

To obtain an array's length, specify array name, dot, and then length.

Note that length is used in two different ways: length is a String method length is an array property

Mnemonic acronym to help you remember when to use parentheses with length:

ANSY (arrays no, strings yes)

1

2

3

Note how an array object's length property gets the array's size.

Page 14: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

15Array length Property and Partially Filled Arrays

import java.util.Scanner;

public class SpeedDialList2{ public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); String[] phoneList = new String[100]; // phone numbers int filledElements = 0; // number of phone numbers String phoneNum; // an entered phone number

System.out.print("Enter phone number (or q to quit): "); phoneNum = stdIn.nextLine(); while (!phoneNum.equalsIgnoreCase("q") && filledElements < phoneList.length) { if (phoneNum.length() < 1 || phoneNum.length() > 16) { System.out.println("Invalid entry." + " Must enter between 1 and 16 characters."); }

1

2

3Array length property does not use ( )'s.

String length method uses ( )'s.

Page 15: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

16Array length Property and Partially Filled Arrays

else

{

phoneList[filledElements] = phoneNum;

filledElements++;

}

System.out.print("Enter phone number (or q to quit): ");

phoneNum = stdIn.nextLine();

} // end while

System.out.println("\nSpeed Dial List:");

for (int i=0; i<filledElements; i++)

{

System.out.println((i + 1) + ". " + phoneList[i]);

} // end for

} // end main

} // end class SpeedDialList2

Page 16: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

17

Partially Filled Arrays

A partially filled array is when you use some of an array's elements, but not all.

If you have a partially filled array, you have to keep track of the number of filled elements in the array so you can process the filled elements differently from the non-filled elements.

In the SpeedDialList2 program, note how the filledElements variable keeps track of the number of phone numbers in the array.

1

Page 17: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

18

Copying an Array

As with all objects and their associated reference variables, if you assign one array reference variable to another array reference variable, both array reference variables then point to the same single array object.

What's the problem with that scenario? More specifically, what's wrong with the following code if the goal is to make a copy of arr1?arr2 = arr1;

1

2

Page 18: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

19

Copying an Array

Usually when you make a copy of an array, you'll want the copy and the original to point to different array objects. To do that, assign array elements one at a time.

For example, suppose you use arrays to hold a store's prices, one array for each month's prices. And you'd like to copy January's price array into February's price array and make a change in February's second price. The program on the next slide does that by assigning array elements one at a time. Here's the program's output: Jan Feb 1.29 1.29 9.99 10.99 22.00 22.00 4.55 4.55 7.35 7.35 6.49 6.49

1

2

Page 19: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

20

Copying an Array

public class ArrayCopy{ public static void main(String[] args) { double[] pricesJanuary = {1.29, 9.99, 22.50, 4.55, 7.35, 6.49}; double[] pricesFebruary = new double[pricesJanuary.length];

for (int i=0; i<pricesJanuary.length; i++) { pricesFebruary[i] = pricesJanuary[i]; } pricesFebruary[1] = 10.99;

System.out.printf("%7s%7s\n", "Jan", "Feb"); for (int i=0; i<pricesJanuary.length; i++) { System.out.printf("%7.2f%7.2f\n", pricesJanuary[i], pricesFebruary[i]); } } // end main} // end class ArrayCopy

1

2

Page 20: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

21

Histograms

A histogram is a graph that displays quantities for a set of categories. It indicates category quantities with bars - shorter bars equate to smaller quantities, longer bars equate to larger quantities.

For example, the histogram on the next slide shows quantities of frozen desserts produced in the United States in 2003.

1

3

2

Page 21: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

22

Histograms

1

2

3

4

5

Page 22: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

23

Histograms

Problem Description: Suppose you have three coins. When you flip all three,

you're curious how likely it is you'll get zero heads, how likely it is you'll get one head, how likely it is you'll get two heads, and how likely it is you'll get three heads. In other words, you're curious about the frequency distribution for the number of heads.

Solution: Write a main method that simulates throwing the

three coins a million times. Print the simulation results in the form of a histogram:

For each of the four cases (zero heads, one head, etc.), print a bar that represents the number of times the case occurred.

To mimic a bar, print a certain number of *'s where each * represents 1% of the total number of simulation iterations.

1

2

Page 23: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

24

Histograms

Output for the coin-flip program:Number of times each head count occurred:

0 124685 ************

1 374759 *************************************

2 375420 **************************************

3 125136 *************

Program implementation tips: Use a four-element frequency array to keep track of the

number of times each head-count value occurs. The frequency[0] element holds the number of times none of the three coins lands heads up. The frequency[1] element holds the number of times one of the three coins lands heads up.

Each element in the frequency array is called a "bin." After each simulation iteration, add 1 to the appropriate bin.

For example, increment the frequency[3] bin if all three of the coins land heads up.

2

3

1

Page 24: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

25

Histogramspublic class CoinFlips{ public static void main(String[] args) { final int NUM_OF_COINS = 3; // number of coins that are flipped final int NUM_OF_REPS = 1000000; // total number of repetitions

// The frequency array holds the number of times a particular number // of heads occurred. int[] frequency; int heads; // number of heads in the current group of flips float fractionOfReps; // Number of times a particular head count occurred // divided by total number of repetitions. int numOfAsterisks; // Number of asterisks in histogram for a // particular head count.

frequency = new int[NUM_OF_COINS + 1]; for (int rep=0; rep<NUM_OF_REPS; rep++) { // perform a group of flips heads = 0; for (int i=0; i<NUM_OF_COINS; i++) { heads += (int) (Math.random() * 2); } frequency[heads]++; // update appropriate bin } // end for

1

2

3

4

5

6

Page 25: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

26

Histograms

1 heads frequency

1st group of flips0 0 0

1 1 0 1 2

2nd group of flips

0 2 0 1

1 3 0

2

3rd group of flips0

1

0···

Page 26: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

27

Histograms

System.out.println( "Number of times each head count occurred:"); for (heads=0; heads<=NUM_OF_COINS; heads++) { System.out.print( " " + heads + " " + frequency[heads] + " "); fractionOfReps = (float) frequency[heads] / NUM_OF_REPS; numOfAsterisks = Math.round(fractionOfReps * 100);

for (int i=0; i<numOfAsterisks; i++) { System.out.print("*"); } System.out.println(); } // end for } // end main} // end class CoinFlips

2

3

4

5

6

1

Page 27: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

28

Searching an array

Often, you'll need to determine whether an array contains a particular value. Here's the pseudocode algorithm for conducting a sequential search for a particular value within a list array:

i ← 0while i < number of filled elements if list[i] equals the searched-for value <do something and stop the loop> increment i

3

4

1

2

5

Page 28: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

29

Searching an array

Problem description: Write a helper method named findStudent that

searches for an id value within an array of student id's. The findStudent method should receive an id

parameter and return the index value of id's location within a studentIds array instance variable.

If id's value is not found, then return -1. As always, use appropriate access modifiers

(public vs. private, class method vs. instance method).

3

5

1

2

4

6

Page 29: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

31

Sorting an Array

Sorting is a very common task in programming. Examples:

Sort e-mails in an inbox – by date, by sender Sort songs – by title, by author Sort student records – by student ID

1

Page 30: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

32

There are many different sorting algorithms with varying degrees of complexity and efficiency. Since this is your first exposure to sorting, we'll cover a simple algorithm - the selection sort algorithm. Here it is:

for (i0; i<list's_length; i++) find the smallest value in list from list[i] down to the bottom of the list swap the found value with list[i]

5

10

-3

20

2

-3

10

5

20

2

list (original)

-3

2

5

20

10

-3

2

5

20

10

-3

2

5

10

20

list (sorted)

0

1

2

3

4

Selection Sort

1

2

Page 31: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

33

Sorting an Array

You could include a sorting method in every class that needs sorting functionality.

For example, you could include: A studentSort method in a Students class that sorts

students by student id. A bookSort method in a Books class that sorts books

by ISBN number. A productSort method in a Products class that sorts

products by product id. But suppose that you want to make a generic

sorting method that receives an array as a parameter (e.g., studentIds, bookISBNs, or productIds) and sorts it.3

4

2

1

Page 32: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

34

To make the sorting method generic so that it can be used by multiple classes, put the sort method in a utility class.

A utility class is a class with general-purpose methods that other classes can easily use. To make the methods easy to use, use class methods (as opposed to instance methods).

Why would it be easy for other classes to use the sort method if the sort method is implemented as a class method?

Sorting an Array

1

Page 33: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

35

If you make the sort method an instance method, then you'll be required to instantiate the sort method's enclosing class prior to calling the sort method. For example, assuming the sort method's enclosing class is named Sort:Sort s = new Sort();

s.sort(studentIds);

On the other hand, if you make the sort method a class method, then you are not required to instantiate the sort method's enclosing class prior to calling the sort method. Instead, you simply need to prefix the sort method call with the class name and then a dot. For example:Sort.sort(studentIds);

Thus, in the interest of simplicity and elegance, let's make the sort method a class method.

Sorting an Array

1

2

Page 34: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

36

Selection Sort

public class Sort{ public static void sort(int[] list) { int j; for (int i=0; i<list.length-1; i++) { j = indexOfNextSmallest(list, i); swap(list, i, j); } } // end sort

private static int indexOfNextSmallest(int[] list, int startIndex) { int min = list[startIndex]; int minIndex = startIndex;

for (int i=startIndex+1; i<list.length; i++) { if (list[i] < min) { min = list[i]; minIndex = i; } } // end for return minIndex; } // end indexOfNextSmallest

1

2

3

4

5

Page 35: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

37

Selection Sort

private static void swap(int[] list, int i, int j) { int temp; temp = list[i]; list[i] = list[j]; list[j] = temp; } // end swap} // end Sort

public class SortDriver{ public static void main(String[] args) { int[] studentIds = {3333, 1234, 2222, 1000}; Sort.sort(studentIds);

for (int i=0; i<studentIds.length; i++) { System.out.print(studentIds[i] + " "); } } // end main} // end SortDriver

1

2

3

4

5

Page 36: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

38

Two-Dimensional Arrays

If you have a group of related data that's organized in a table format, consider using a two-dimensional array.

Two-dimensional arrays use the same basic syntax as one-dimensional arrays except for a second pair of []'s.

the first index identifies the row and the second index identifies the column position within a row.

For example, here's a two-row by three-column array named x:

1

2

xhow to access each

element

0 1 2

0 8 -2 4 x[0][0] x[0][1]x[0][2]

1 1 0 5 x[1][0] x[1][1]x[1][2]

column indexes

row indexes

Page 37: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

39

Two-Dimensional Arrays

As with one-dimensional arrays, there are two ways to assign values into a two-dimensional array’s elements: 1) an array initializer, 2) assignment statements.

Here’s how you can declare the previous slide's x array and assign values into its elements, using an array initializer:int[][] x = {{8,-2,4}, {1,0,5}};

You can use the array initializer technique only if you know the assigned values when you first declare the array. Otherwise, you need to provide array element assignment statements that are separate from the array's declaration and creation.

1

2

initializer for a 2-row by 3-column array

Page 38: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

40

Two-Dimensional Arrays

The following code fragment declares and creates the x array in one statement, and assigns values to x's elements in a separate statement.int[][] x = new int[2][3];

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

{

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

{

System.out.print(

"Enter value for row " + i + ", col " + j);

x[i][j] = stdIn.nextInt();

} // end for j

} // end for i

2

3

Assign a value to the element at row i column j.

Declare and create a 2-row by 3-column array.

1

Page 39: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

41

Two-Dimensional Arrays

Bottom line: To loop through the rows in a two-dimensional array, use <array-name>.length . And to loop through the elements within a particular row, use <array-name>[0].length. For example:for (int i=0; i<x.length; i++){ for (int j=0; j<x[0].length; j++) { ...

3

1 2

Page 40: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

42

Two-Dimensional Arrays

The upcoming FlightTimes program: Uses a two-dimensional array to store this table of

flight times between cities:

Wch Top KC Col StL

Wch 0 22 30 42 55

Top 23 0 14 25 37

KC 31 9 0 11 28

Col 44 27 12 0 12

StL 59 41 30 14 0

Contains a promptForFlightTime method that prompts the user for a departure city and a destination city and prints the flight time for that flight.

Contains a displayFlightTimesTable method that prints the table.

2

1

3

It takes 25 minutes to fly from Topeka, KS to Columbia, MO.

Page 41: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

43

Two-Dimensional Arrays

public class FlightTimesDriver{ public static void main(String[] args) { int[][] flightTimes = { {0, 22, 30, 42, 55}, {23, 0, 14, 25, 37}, {31, 9, 0, 11, 28}, {44, 27, 12, 0, 12}, {59, 41, 30, 14, 0} }; // Define terminals in the Kansas-Missouri region. String[] cities = {"Wch", "Top", "KC", "Col", "StL"}; FlightTimes ft = new FlightTimes(flightTimes, cities);

System.out.println("\nFlight times for KansMo Airlines:\n"); ft.displayFlightTimesTable(); System.out.println(); ft.promptForFlightTime(); } // end main} // end class FlightTimesDriver

1

2

3

Page 42: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

44

Two-Dimensional Arrays

import java.util.Scanner;

public class FlightTimes{ private int[][] flightTimes; // table of flight times private String[] cities; // names of cities in flightTimes table

public FlightTimes(int[][] ft, String[] c) { flightTimes = ft; cities = c; } //******************************************** // This method prompts the user for departure and destination cities // and prints the associated flight time. public void promptForFlightTime() { Scanner stdIn = new Scanner(System.in); int departure; // index for departure city int destination; // index for destination city

1

Page 43: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

45

Two-Dimensional Arrays

for (int i=0; i<cities.length; i++) { System.out.println(i+1 + " = " + cities[i]); } System.out.print("Enter departure city's number: "); departure = stdIn.nextInt() - 1; System.out.print("Enter destination city's number: "); destination = stdIn.nextInt() - 1; System.out.println("Flight time = " + flightTimes[departure][destination] + " minutes."); } // end promptForFlightTime //******************************************** // This method prints a table of all flight times.

<Insert displayFlightTimesTable method here.>

} // end class FlightTimes

1

2

Page 44: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

47

Arrays of Objects

Suppose you need to keep track of total sales for each sales clerk in a department store.

In the following clerks array, each array element holds a reference for a SalesClerk object.

Each SalesClerk object holds a sales clerk's name and a total-sales value for the sales clerk.

If sales clerk Amanda sells two items for $55.45 and $22.01, then you'd like to store 77.46 for her total-sales value.

1

2

clerks

clerks[0]

clerks[1]

clerks[2]

clerks[3] null

Daniel, 6.25

Josh, 58.12

Amanda, 77.46

Page 45: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

48

Arrays of Objects

Show how the clerks array gets filled with the input shown below.

clerks

null

null

null

null

1

2

input filledElements

Daniel 0

6.25

Josh

58.12

Amanda

40

Daniel

-6.25

Josh

12.88

3

Page 46: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

49

Arrays of Objects

import java.util.Scanner;

public class SalesClerksDriver{ public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); SalesClerks clerks = new SalesClerks(2); String name;

System.out.print("Enter clerk's name (q to quit): "); name = stdIn.nextLine(); while (!name.equals("q")) { System.out.print("Enter sale amount: "); clerks.addSale(name, stdIn.nextDouble()); stdIn.nextLine(); // flush newline System.out.print("Enter clerk's name (q to quit): "); name = stdIn.nextLine(); } // end while clerks.dumpData(); } // end main} // end SalesClerksDriver

2

1

3

4

5

6

Page 47: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

50

Arrays of Objectsclass SalesClerks{ private SalesClerk[] clerks; // contains names and sales private int filledElements = 0; // number of elements filled

//***********************************************************

public SalesClerks(int initialSize) { clerks = new SalesClerk[initialSize]; } // end SalesClerks constructor

//***********************************************************

// Process a sale for the clerk whose name is passed in. // If the name is not already in the clerks array, // create a new object and insert a reference to it in the // next array element, doubling array length if necessary.

public void addSale(String name, double amount) { int clerkIndex = findClerk(name);

if (clerkIndex == -1) // add a new clerk { if (filledElements == clerks.length) { doubleLength(); }

2

1

3

4

5

Page 48: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

51

Arrays of Objects

clerkIndex = filledElements; clerks[clerkIndex] = new SalesClerk(name); filledElements++; } // end if

clerks[clerkIndex].adjustSales(amount); } // end addSale

//**********************************************************

// Print all the data - sales clerk names and sales.

public void dumpData() { for (int i=0; i<filledElements; i++) { System.out.printf("%s: %6.2f\n", clerks[i].getName(), clerks[i].getSales()); } } // end dumpData

//**********************************************************

2

1

Page 49: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

52

Arrays of Objects

// Search for the given name. If found, return the index. // Otherwise, return -1.

private int findClerk(String name) { for (int i=0; i<filledElements; i++) { if (clerks[i].getName().equals(name)) { return i; } } // end for return -1; } // end findClerk

//**********************************************************

// Double the length of the array. private void doubleLength() { SalesClerk[] clerks2 = new SalesClerk[2 * clerks.length]; System.arraycopy(clerks, 0, clerks2, 0, clerks.length); clerks = clerks2; } // end doubleLength} // end class SalesClerks

1

2

The arraycopy method copies the first argument's array (starting at the second argument's position) to the third argument's array (starting at the fourth argument's position). The fifth argument specifies the number of elements that are to be copied.

Page 50: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

53

Arrays of Objectspublic class SalesClerk{ private String name; // sales clerk's name private double sales = 0.0; // total sales for clerk

//*******************************************************

public SalesClerk(String name) { this.name = name; }

//*******************************************************

public String getName() { return name; }

public double getSales() { return sales; }

//*******************************************************

// Adjust clerk's total sales by adding the passed-in sale.

public void adjustSales(double amount) { sales += amount; }} // end class SalesClerk

2

1

3

Page 51: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

54

Arrays of Objects

Beware: To create an array of objects, you must instantiate the

array with the new operator, and you must also instantiate each object that's stored in the array with individual new operators.

For example, the SalesClerks constructor instantiates an array of SalesClerk objects like this:

clerks = new SalesClerk[maxClerks];

You might think that since the above instantiation specifies maxClerks number of SalesClerk objects, the JVM instantiates all the SalesClerk objects.

On the contrary, the JVM only instantiates an array object and each array element holds null.

To fill up the clerks array with SalesClerk objects, you need to instantiate the SalesClerk objects individually.2

1

Page 52: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

55

The ArrayList Class

The ArrayList class provides the basic functionality that comes with a standard array, plus it provides additional functionality.

The basic functionality: An ArrayList stores an ordered collection of values and allows access to the values via an index.

The added functionality: An ArrayList grows and shrinks dynamically by inserting and deleting elements at any specified location.

1

Page 53: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

56How to Create an ArrayList Object

The ArrayList class is defined in the Java API's java.util package, so for files that use the ArrayList class, import it like this:

import java.util.ArrayList;

To initialize an ArrayList reference variable, use this syntax:

ArrayList<element-type> reference-variable =

new ArrayList<element-type>();

For example, here's how to initialize an ArrayList reference variable named students:

ArrayList<Student> students = new ArrayList<Student>();

Compare the above ArrayList initialization to this standard-array initialization:Student[] students = new Student[100];

4

2

1

3

Page 54: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

57How to Create an ArrayList Object

What are the syntax differences between the ArrayList example and the standard-array example? With the ArrayList example:1. Use angled brackets to specify the type for the

elements.2. <element-type> must be a class name (not a primitive).3. Do not specify the number of elements (because

ArrayList objects start out with no elements).

1 3

4

2

Page 55: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

58Adding Elements to an ArrayList Object

To add an element to the end of an ArrayList object, use this syntax:ArrayList-reference-variable.add(item);

The item that's added must be the same type as the type specified in the ArrayList's declaration.

Write a code fragment that creates this ArrayList object:

2

1

4

3

colors

0 "red"

1 "green"

2 "blue"

Page 56: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

59

Java API

API stands for application programming interface. The Java API is the interface to Sun's huge library of pre-built

Java classes. As a programmer, you don't need to know the internals of

those classes; you just need to know how to use them. Or said another way, you just need to know how to interface with them.

To interface with them, you need to use their public methods. To use a method, you need to know what type of argument(s)

to pass to it and what type of value it returns. A method's API shows the method's parameters and its return type.

The standard way to show that information is to show the method's heading. For example, here's the API heading for the Math class's pow method:

public static double pow(double num, double power)

2

1

4

3

Page 57: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

60How to Access an Element Within an ArrayList

With standard arrays, you use square brackets to access and update an element. ArrayList objects don't use square brackets. Instead, they use a get method to access an element and a set method to update an element.

Here's the API heading for the ArrayList's get method:

public E get(int index)

Semantics: The index parameter specifies the position of the desired

element within the ArrayList calling object. As with standard arrays, the first element is at position 0, the second element is at position 1, etc.

If index refers to a nonexistent element, then a runtime error occurs.

If index is valid, then get returns the element at the specified position.

2

1

Page 58: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

61How to Access an Element Within an ArrayList

Note the E return type for the ArrayList's get method:public E get(int index)

The E stands for element. It represents the data type of the ArrayList's elements. It's the same as the element-type specified in the ArrayList's initialization:ArrayList<element-type> reference-variable =

new ArrayList<element-type>();

1

2

Page 59: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

62

How to Update an ArrayList Object

The set method allows you to assign a value to an ArrayList element. Here's its API heading:public E set(int index, E elem)

Semantics: The index parameter specifies the position of the

element you're interested in. If index refers to a nonexistent element, then a

runtime error occurs. If index is valid, then set assigns the elem parameter

to the specified element, overlaying whatever was there originally.

E represents the data type of the ArrayList's elements.

1

Page 60: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

63

How to Update an ArrayList Object

Draw a picture of the colors ArrayList after this code fragment executes:String mixedColor;

ArrayList<String> colors = new ArrayList<String>();

colors.add("red");

colors.add("green");

colors.add("blue");

mixedColor =

colors.get(0) + colors.get(1);

colors.set(2, mixedColor);1

Page 61: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

64

Additional ArrayList Methods

public void add(int index, E elem) Starting with the specified index position, shift the original elements

to higher-indexed positions. Then insert the elem parameter at the specified index position.

public void clear() Remove all elements from the list.

public int indexOf(E elem) Search for the first occurrence of the elem parameter within the list.

If it's found, return its index position. If it's not found, return -1. public boolean isEmpty()

Return true if the list contains no elements. public E remove(int index)

Remove the element at the specified index position, shift all higher-indexed elements to lower-indexed positions, and return the removed element.

public int size() Return the number of elements in the list.

2

1

3

4

Page 62: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

66

Example ArrayList Program

import java.util.ArrayList;

public class Survivor{ public static void main(String[] args) { int loserIndex; String loser; ArrayList<String> tribe = new ArrayList<String>(); tribe.add("Richard"); tribe.add("Jerri"); tribe.add("Colby"); tribe.add("Amber"); tribe.add("Rupert"); loserIndex = (int) (Math.random() * 5); loser = tribe.remove(loserIndex); System.out.println("Sorry, " + loser + ". The tribe has spoken. You must leave immediately."); System.out.println("Remaining: " + tribe); } // end main} // end Survivor2

1

Page 63: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

67Printing or Concatenating an ArrayList

If you attempt to print or concatenate an ArrayList, the ArrayList returns a comma-separated list of ArrayList elements surrounded by square brackets ([]).

For example, in the Survivor program, if Colby is removed, the last line prints this:Remaining: [Richard, Jerri, Amber, Rupert]

1

Page 64: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

68Storing Primitives in an ArrayList

As mentioned previously, ArrayLists store references. For example, in the Survivor program, tribe is an ArrayList of strings, and strings are reference types.

If you need to store primitives in an ArrayList, you can't do it directly, but you can do it if the primitives are wrapped up in wrapper classes.

With the advent of Java 5.0, the "wrapping up" process is done automatically behind the scenes. For ArrayLists, it's done automatically as long as you use a wrapper class rather than a primitive for your ArrayList declaration.

The StockAverage program on the next slide reads int stock values and stores them in an ArrayList. After all stock values are entered, the program calculates the average stock value.

Why is an ArrayList appropriate for calculating a stock average?

2

1

3

4

5

Page 65: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

69Storing Primitives in an ArrayList

import java.util.Scanner;import java.util.ArrayList;

public class StockAverage{ public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); ArrayList<Double> stocks = new ArrayList<Double>(); double stock; // a stock value double stockSum = 0; // sum of stock values

System.out.print("Enter a stock value (-1 to quit): "); stock = stdIn.nextDouble();

while (stock >= 0) { stocks.add(stock); System.out.print("Enter a stock value (-1 to quit): "); stock = stdIn.nextDouble(); } // end while

1

Must be a wrapper class, not a primitive.

Automatic boxing takes place here.

2

3

Page 66: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

70Storing Primitives in an ArrayList

for (int i=0; i<stocks.size(); i++) { stock = stocks.get(i); stockSum += stock; }

if (stocks.size() != 0) { System.out.printf("\nAverage stock value = $%.2f\n", stockSum / stocks.size()); } } // end main} // end class StockAverage

1 Where does automatic unboxing take place?

2

Page 67: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

71ArrayList Example Using Anonymous Objects and the For-Each Loop

When storing objects in an ArrayList, it's common to create an object and add it to the ArrayList all in the same statement.

For example, the upcoming BearStore program stores Bear objects in an ArrayList. In storing a Bear object, the program creates a Bear object and adds it to the bears ArrayList, all in the same statement:

bears.add(new Bear("Acme", "brown teddy"));

An anonymous object is an object that's instantiated but it's not stored in a variable (and with no variable, there's no name for it; thus, we say it's "anonymous").

1

2

Page 68: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

72ArrayList Example Using Anonymous Objects and the For-Each Loop

import java.util.Scanner;import java.util.ArrayList;

public class BearStore{ ArrayList<Bear> bears = new ArrayList<Bear>(); //**********************************************************

// Fill store with specified number of standard teddy bears. public void addStdBears(int num) { for (int i=0; i<num; i++) { bears.add(new Bear("Acme", "brown teddy")); } } // end addStdBears

anonymous object

1

Page 69: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

73ArrayList Example Using Anonymous Objects and the For-Each Loop

//**********************************************************

// Fill store with specified number of customized bears. public void addUserSpecifiedBears(int num) { for (int i=0; i<num; i++) { bears.add(getUserSpecifiedBear()); } } // end addUserSpecifiedBears

//**********************************************************

// Prompt user for a customized bear name and return bear. private Bear getUserSpecifiedBear() { Scanner stdIn = new Scanner(System.in); String maker, type; System.out.print("Enter bear's maker and type separated by a space: "); maker = stdIn.next(); type = stdIn.next(); return new Bear(maker, type); } // end getUserSpecifiedBear

anonymous object

Page 70: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

74ArrayList Example Using Anonymous Objects and the For-Each Loop

//**********************************************************

// Print all the bears in the store. public void displayInventory() { for (Bear bear : bears) { bear.display(); } } // end displayInventory //**********************************************************

public static void main(String[] args) { BearStore store = new BearStore(); store.addStdBears(3); store.addUserSpecifiedBears(2); store.displayInventory(); } // end main} // end BearStore class

Page 71: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

75ArrayList Example Using Anonymous Objects and the For-Each Loop

public class Bear{ private final String MAKER; // bear's manufacturer private final String TYPE; // type of bear //**********************************************************

public Bear(String maker, String type) { MAKER = maker; TYPE = type; }

public void display() { System.out.println(MAKER + " " + TYPE); }} // end Bear class

Page 72: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

76

Anonymous Objects

The bear store program contains several specific examples of using anonymous objects. In general, you'll see anonymous objects being used in two circumstances: Passing a newly created object into a method or

constructor. For example:bears.add(new Bear("Acme", "brown teddy"));

Returning a newly created object from a method. For example:return new Bear(maker, type);

Page 73: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

77

For-Each Loop

Note the for-each loop in the BearStore's displayInventory method:public void displayInventory()

{

for (Bear bear : bears)

{

bear.display();

}

} // end displayInventory

For-each loop syntax for an ArrayList:for (<element-type> <element-name> : <ArrayList-reference-variable>)

Read this as "for each bear in bears, …"For each iteration through the loop, bear accesses the next element in the bears ArrayList.

Page 74: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

78

For-Each Loop

Note that using the for-each loop is an option, not a requirement. Here's an alternative displayInventory implementation that uses a standard for loop:public void displayInventory()

{

for (int i=0; i<bears.size(); i++)

{

bears.get(i).display();

}

} // end displayInventory

The for-each loop implementation is preferred because it is simpler.

1

Page 75: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

79

For-Each Loop

Be aware that you can use for-each loops for more than just ArrayLists. You can also use them with standard arrays.

Here's a for-each loop example that prints the numbers in a primes array:int[] primes = {1, 2, 3, 5, 7, 11};

for (int p : primes)

{

System.out.println(p);

}

1

Page 76: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

80

For-Each Loop

For-each loop limitations: It's new with Java 5.0, so it won't work with older

compilers.

Can only be used with things that have elements - Java API collections (the ArrayList is a Java API collection) and arrays.

Here's a for-each loop example that prints the numbers in a primes array:int[] primes = {1, 2, 3, 5, 7, 11};

for (int p : primes)

{

System.out.println(p);

}

1

2

Page 77: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

81

For-Each Loop

Be aware of several issues when using a for-each loop: It's new with Java 5.0, so it won't work with older

compilers. The for-each loop doesn't use an index variable to loop

through its elements. That can be a benefit in that it leads to less cluttered code. But it's a drawback if there's a need for an index within the loop.

For example, given the primes array in the previous slide, which type of loop (standard or for-each) should you use to print the following?primes[0] = 1primes[1] = 2...primes[3] = 11

As a practice exercise, provide a standard for loop that prints the above and also provide a for-each loop that prints the above.

3

1

2

Page 78: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

82

ArrayList Objects Versus Standard Arrays

2

1

3

Benefits of an ArrayList Over a Standard Array

Benefits of a Standard Array Over an ArrayList

1. It's easy to increase the size of an ArrayList – just call add.

1. A standard array uses []'s to access array elements (which is easier than using get and set methods).

2. It's easy for a programmer to insert or remove an element to or from the interior of an ArrayList – just call add or remove and specify the element's index position.

2. A standard array is more efficient with storing primitive values. 4

Page 79: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

83

Chapter 10 - Quiz Questions

1. The book uses the acronym ANSY as a mnemonic device. What does ANSY stand for?

a) a new sorting yieldb) arrays never say yieldc) arrays no, strings yes

2. Which of the following is a syntactically correct Java example of accessing an element in a two-dimensional array named table?

a) table[2][2]

b) table[2, 2]

c) table(2, 2)

Page 80: 1 Chapter 10 – Arrays and ArrayList s Array Basics Array Declaration Array Creation Array Element Initialization Array Default Values Array length Property

84

Chapter 10 - Quiz Questions

3. In the book, what example is given for a three-dimensional array?

a) Keeping track of rainfall using latitude, longitude, and time of day.

b) Keeping track of airplane travel times using departure city, destination city, and type of aircraft (jet-fuel, solar-powered, wind-powered).

c) Keeping track of tic-tac-toe squares in a three-dimensional tic-tac-toe game.4. In the book, what television show was used as part of an ArrayList example?

a) Jeopardyb) Survivorc) Desperate Housewives