35
Chapter 6 Arrays and Array Lists

Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Embed Size (px)

Citation preview

Page 1: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Chapter 6Arrays and Array Lists

Page 2: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Array Basics

An array is used to store a collection of data, but often we find it more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and numbers[99] to represent individual variables.

We declare the reference to an array by first giving the data type followed by square brackets and then the name of the array being declared.

We use the word new to reserve space in memory for the array of variables followed by the data type and the number of data elements in square brackets.

double[] aList = new double[100];

data type array name data type size of array

Page 3: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Declaring and Using Arrays

public class arrayDemo{ public static void main(String[] args) { double[] values;

values = new double[10];

for(int i=0;i<10;i++) values[i] = 0;

values[4] = 35;

System.out.println("values[2] = " + values[2]); System.out.println("values[4] = " + values[4]); }}

a referenceto the listof values

Page 4: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Ways to Declare the Values in an Array

In addition, we will learn how to read values from a text file and load them into an array.

Page 5: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Array Reference

Page 6: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Partially Filled Arrays

Page 7: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Often you will have to store a large number of values during the execution of a program. Suppose, for instance, that you need to read 10 numbers, compute their average, and find out how many numbers are above the average.

Case Study: Analyze a List of Numbers

Page 8: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

An Example Array

Page 9: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Array Initializers

Java has a shorthand notation, known as the array initializer, which combines in one statement declaring an array, creating an array, and initializing, using the following syntax:

elementType[] arrayRefVar = {value0, value1, ..., valuek};

For example,double[ ] myList = {1.9, 2.9, 3.4, 3.5};

This statement declares, creates, and initializes the array myList with four elements, which is equivalent to the statements shown below:

double[ ] myList = new double[4];

myList[0] = 1.9;

myList[1] = 2.9;

myList[2] = 3.4;

myList[3] = 3.5;

Page 10: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Case Study: Deck of Playing Cards

Problem: Create an array that represents a deck of 52 playing cards. Build methods to shuffle and deal cards from the deck and describe the cards by their suit and rank.

Analysis:

An array of 52 values [0..51] can represent the 52 cards.

The suit (spades, hearts, diamonds, clubs) can be encoded using,

suit_num = card_val/4

spades=0, hearts=1, diamonds=2, clubs=3 Shuffling can be achieved by swapping random pairs of values in the array.

Dealing can be achieved by incrementing an index starting with 0 (top of deck) and ending at 51 (bottom of deck)

Page 11: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

DeckOfCards.java

sample run

Page 12: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Copying Arrays

Page 13: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Copying Arrays (cont.)

Page 14: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Passing an Array to a Method

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following program demonstrates how a method can display the elements in an int array:

note that arrays are adifferent length

printArray can accept anint array of any size

Page 15: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

1 3 5 7 9 9 7 5 3 1

Passing an Array from a Method

Page 16: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Case Study: Counting Characters

Problem: Build a program that generates a random list of 1000 characters and then counts and displays the number of occurences of each letter.

The lowercase letters have an integer value called the ASCII value. Java allows us to directly convert from char to int and back by type casting.

(int)'a' is equal to 97

(char) 97 is equal to 'a'

We can generate a random list of lowercase letters using the Math.random() method. Note that Java permits us to directly access the ASCII value of characters in arithmetic statements

chr[i] = (char)('a' + Math.random() * ('z' - 'a' + 1))

We want to count the number of occurences of each letter in our generated list so we can use the ASCII value of the letter itself to generate the index of the count array to be incremented.

count[(int)chr[i] - 97] += 1

Page 17: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Counting Characters Java Program

Page 18: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

nghlrhfoxcorpideetazoqdbjysettoulnnrfbmddwtyfccmmcifioqvhvvnuuzgdgwhfzuzdezwvtpqmchkwwvvnlhrbjqmuyfavtgtfetsvbwvpdockblhfdzbctknlstnmjivlgdkfyhhkywwmidyfceyiqcpurzbgxmuyduqrwhndosxtbuaafjbieyynguvagxslgohrpjkmixqucxeywivxllosetxfoncwhbdxdpxuowxnvhckgooxbfnmiakplnspcvrwcgvgvqxpbacsvvatzfjbdctksrznqhjccmxoepyekowtazerqkxuywirkflqmlytnscscevuvhrkbbhxhmytzgevvbmxfngtlufbzvhuiatolregtqrnfrkrbvjakvytasrssltqeeydblrvbdavscfhoqlysdtrvmpaqufsdvnthcnitnjaczrofvufzbzjqgdkqhlfxbmuojkxfpnmjwnsjasvdtzmnpynoyrqdvqbwhefdgtfybgdjkbevxgoxidmzycwhtmgbbktptmvxinpgkgkoakseeiouvxgckbsqofeajvwjesmliwubusalywwrlolyrxwpqgppwncoisliniqstvqlaklhygpulrlwlyyyuegqgcigsdfqlmtuvwubcoygqpalxfwwnsbwbndnmsaonuhoujcxtmkufkdiqbwptzjlvenecjihetiwlnlprsthvmgmetkykvnzutifqtxdwqdbtdoxozpxhggyzxpfnfircnkagwbyjektwyjmgwcdqtygjhxulp

There are 29 a'sThere are 40 b'sThere are 38 c'sThere are 40 d'sThere are 39 e'sThere are 44 f'sThere are 45 g'sThere are 34 h'sThere are 34 i'sThere are 24 j'sThere are 37 k'sThere are 43 l'sThere are 37 m'sThere are 49 n'sThere are 38 o'sThere are 31 p'sThere are 39 q'sThere are 30 r'sThere are 35 s'sThere are 49 t'sThere are 40 u'sThere are 44 v'sThere are 39 w'sThere are 47 x'sThere are 47 y'sThere are 28 z's

A total of 1000 characters

Counting Characters: Results

1000 lowercase letters

letter counts

checking the total

Page 19: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

public class VarArgsDemo { public static void main(String[] args) { printMax(34, 3, 3, 2, 56.5); printMax(new double[]{1, 2, 3}); } public static void printMax(double... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; } double result = numbers[0]; for (double val : numbers) if ( val > result) result = val; System.out.println("The max value is " + result); }}

Methods can Accept Variable Sized Arguments

accepts a list of doublesof arbitrary length

If there are no argumentsthen length = 0

looking for max value inthe list, numbers[ ]

The max value is 56.5The max value is 3.0

Page 20: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Method to Generate a Random Array of doubles

public class arrayDemo{ public static void main(String[] args) { double[] values; values = array_gen(10, -20.0, 30.0); for(double val : values) System.out.println(val); } public static double[]array_gen(int n, double min, double max) { double[] array = new double[n]; double range = max - min; for(int i=0;i<n;i++) array[i] = Math.random()*range + min; return array; }}

16.08298258073998-19.8372986329335467.188783600147882-14.48977454494754-1.09991793380482865.7798441822651482.415951962355151714.60749013952067-5.464885809054125.26053031236582

Page 21: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Common Array Algorithms

Filling - assigning values to each element of an Array.

Sum and Average - Computing the sum or the average of the values in an Array.

Minimum and Maximum - Finding the smallest or largest value in an Array.

Searching for a Value - Looking for a particular value in an Array.

Deleting an Element - Removing a particlar value or element from an Array.

Inserting an Element - Adding a value and/or element to an Array.

Swapping a Pair of Elements - Exchanging the positions of two values in an Array.

Reading and Writing Files - Loading Array data from or storing data onto the hard drive.

Copying an Array - Creating a separate Array with the same values of an existing Array.

Sorting the Values - Arranging the values in an Array in ascending or descending order.

Page 22: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Case Study: SearchFinding an Item in a List

Problem: Build a method that returns the index (location) of a specified item in a list (or a -1 if item is not in list).

We will generate 100 integers in the range of [0..99]

There will likely be repeated values and missing values in this range

If the specified value for which we are searching is in the list then the method will return the index (location) of the value in the list. Since there may be more than on instance of the value the method can be designed to return the first value encountered or the last.

Page 23: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

linsearch( ) Java ProgramA linear search involves stepping through the values of an array on at a time until a particlar value is found. This process may be implemented as a Boolean function that returns true if the value is in the array, or it may display the value itself, its location in the array or some message about the value.

Page 24: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Sample Runs

Page 25: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Alternative linsearch( ) Method

Page 26: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

1

2

3

5

0

7

9

6

4

8

list

i

j

tmp

1

2

3

5

0

7

9

6

4

8

list

i

j

1

2

3

5

0

7

9

6

4

8

list

0

2

3

5

1

7

9

6

4

8

list

i

j

A Simple Sort Algorithm

outer loop (i)runs from i=0

to i<n-1

inner loop (j)runs from j=i+1

to j<n

whenlist[i]>list[j]values areswapped

total number ofkey comparisonsis O(n2/2) = O(n2)

There are a wide variety of sorting algorithms, most of which involve the use of a pair of nested loops.

Page 27: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Simple Sort Program

Page 28: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Saving a Listfile I/O class for java

Write to file ratherthan standard output

close file when done

Page 29: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Reading a List from a Text File

Page 30: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Searching a Sorted ListIf a list is sorted, we don't have to test every item to find a particular value or to verify that the value is not in the list. For example: In the list below we will search for the value 20.

2

2

3

5

6

8

9

12

20

42

list

2

2

3

5

6

8

9

12

20

42

list

2

2

3

5

6

8

9

12

20

42

list

2

2

3

5

6

8

9

12

20

42

list

2

2

3

5

6

8

9

12

20

42

list

make firstguess at list

mid-pointindex = 4

list[4]<20so val notin 1st half

of list

0

1

2

.

.

9

next guessat mid-pointof sub-listlist[7]<20

next guesslist[9]>20one item

remaining

max numberkey comparisons

O(log2n)

Page 31: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Binary Search

set the initial lo and hi index (why set lo = -1 ?)

iv = index of current guessif guess too low drop 1st half of listif guess too high drop 2nd half

if guess correct display and quit

if not in list display message and quit

We can use a Binary Search method to search for a particlar value in a sorted list.

Page 32: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Two-Dimensional Arrays

Single-dimensional arrays are like lists. Much of the data we deal with every day comes to us in the form of a table or a matrix which are examples of two-dimensional arrays. One of the most common forms of two-dimensional data we encounter is the spreadsheet. In fact, when we build spreadsheets that include cells whose values depend on the values in other cells, we are programming.

Page 33: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

In Java, you obtain a two-dimensional array by supplying the number of rows and columns. For example, new int[7][3] is an array with seven rows and three columns. You store a reference to such an array in a variable of type int[][]. Here is a complete declaration of a two-dimensional array, suitable for holding our medal count data:

final int COUNTRIES = 7;final int MEDALS = 3;int[][] counts = new int[COUNTRIES][MEDALS];

Alternatively, you can declare and initialize the array by grouping each row:

int[][] counts ={

{ 1, 0, 1 },{ 1, 1, 0 },{ 0, 0, 1 },{ 1, 0, 0 },{ 0, 1, 1 },{ 0, 1, 1 },{ 1, 1, 0 }

};

As with one-dimensional arrays, you cannot change the size of a two-dimensional array once it has been declared.

Declaring Two-Dimensional Arrays

Page 34: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

Accessing Elements

To access a particular element in the two-dimensional array, you need to specify two index values in separate brackets to select the row and column, respectively

int medalCount = counts[3][1];

To access all elements in a two-dimensional array, you use two nested loops. For example, the following loop prints all elements of counts:

for (int i = 0; i < COUNTRIES; i++){// Process the ith rowfor (int j = 0; j < MEDALS; j++){// Process the jth column in the ith rowSystem.out.printf("%8d", counts[i][j]);}System.out.println(); // Start a new line at the end of the row}

Page 35: Chapter 6 Arrays and Array Lists. Array Basics An array is used to store a collection of data, but often we find it more useful to think of an array as

public class Medals{ public static void main(String[] args) { final int COUNTRIES = 7; final int MEDALS = 3; String[] countries = { "Canada","China","Germany","Korea", "Japan","Russia","United States" }; int[][] counts = {{ 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 }}; //table header System.out.println("Country Gold Silver Bronze Total");

for (int i = 0; i < COUNTRIES; i++) { System.out.printf("%7s", countries[i]); // first column of table int total = 0; for (int j = 0; j < MEDALS; j++) // medal data { System.out.printf("%8d", counts[i][j]); total = total + counts[i][j]; } System.out.printf("%8d\n", total); // rightmost column of table } }}

Country Gold Silver Bronze Total Canada 1 0 1 2 China 1 1 0 2Germany 0 0 1 1 Korea 1 0 0 1 Japan 0 1 1 2 Russia 0 1 1 2 USA 1 1 0 2

Two-Dimensional Array Parameters