Download presentation
1
Chapter 6 Arrays and Array Lists
2
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
3
Declaring and Using Arrays
a reference to the list of values 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]); } }
4
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.
5
Array Reference
6
Partially Filled Arrays
7
Case Study: Analyze a List of Numbers
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.
8
An Example Array
9
elementType[] arrayRefVar = {value0, value1, ..., valuek};
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;
10
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)
11
DeckOfCards.java sample run
12
Copying Arrays
13
Copying Arrays (cont.)
14
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 a different length printArray can accept an int array of any size
15
Passing an Array from a Method
16
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
17
Counting Characters Java Program
18
Counting Characters: Results
nghlrhfoxcorpideetazoqdbjysettoulnnrfbmddwtyfccmmc ifioqvhvvnuuzgdgwhfzuzdezwvtpqmchkwwvvnlhrbjqmuyfa vtgtfetsvbwvpdockblhfdzbctknlstnmjivlgdkfyhhkywwmi dyfceyiqcpurzbgxmuyduqrwhndosxtbuaafjbieyynguvagxs lgohrpjkmixqucxeywivxllosetxfoncwhbdxdpxuowxnvhckg ooxbfnmiakplnspcvrwcgvgvqxpbacsvvatzfjbdctksrznqhj ccmxoepyekowtazerqkxuywirkflqmlytnscscevuvhrkbbhxh mytzgevvbmxfngtlufbzvhuiatolregtqrnfrkrbvjakvytasr ssltqeeydblrvbdavscfhoqlysdtrvmpaqufsdvnthcnitnjac zrofvufzbzjqgdkqhlfxbmuojkxfpnmjwnsjasvdtzmnpynoyr qdvqbwhefdgtfybgdjkbevxgoxidmzycwhtmgbbktptmvxinpg kgkoakseeiouvxgckbsqofeajvwjesmliwubusalywwrlolyrx wpqgppwncoisliniqstvqlaklhygpulrlwlyyyuegqgcigsdfq lmtuvwubcoygqpalxfwwnsbwbndnmsaonuhoujcxtmkufkdiqb wptzjlvenecjihetiwlnlprsthvmgmetkykvnzutifqtxdwqdb tdoxozpxhggyzxpfnfircnkagwbyjektwyjmgwcdqtygjhxulp There are 29 a's There are 40 b's There are 38 c's There are 40 d's There are 39 e's There are 44 f's There are 45 g's There are 34 h's There are 34 i's There are 24 j's There are 37 k's There are 43 l's There are 37 m's There are 49 n's There are 38 o's There are 31 p's There are 39 q's There are 30 r's There are 35 s's There are 49 t's There are 40 u's There are 44 v's There are 39 w's There are 47 x's There are 47 y's There are 28 z's A total of 1000 characters 1000 lowercase letters letter counts checking the total
19
Methods can Accept Variable Sized Arguments
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); } } accepts a list of doubles of arbitrary length If there are no arguments then length = 0 looking for max value in the list, numbers[ ] The max value is 56.5 The max value is 3.0
20
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; } }
21
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.
22
Case Study: Search Finding 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.
23
linsearch( ) Java Program
A 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.
24
Sample Runs
25
Alternative linsearch( ) Method
26
A Simple Sort Algorithm
There are a wide variety of sorting algorithms, most of which involve the use of a pair of nested loops. list list list list i 1 i 1 1 j 2 2 2 i 2 3 3 3 3 5 5 5 5 j tmp j 1 7 7 7 7 9 9 9 9 6 6 6 6 4 4 4 4 8 8 8 8 outer loop (i) runs from i=0 to i<n-1 inner loop (j) runs from j=i+1 to j<n when list[i]>list[j] values are swapped total number of key comparisons is O(n2/2) = O(n2)
27
Simple Sort Program
28
Saving a List file I/O class for java Write to file rather
than standard output close file when done
29
Reading a List from a Text File
30
Searching a Sorted List
If 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. list list list list list 1 2 . 9 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 5 5 5 5 5 6 6 6 6 6 8 8 8 8 8 9 9 9 9 9 12 12 12 12 12 20 20 20 20 20 42 42 42 42 42 make first guess at list mid-point index = 4 list[4]<20 so val not in 1st half of list next guess at mid-point of sub-list list[7]<20 next guess list[9]>20 one item remaining max number key comparisons O(log2n)
31
Binary Search set the initial lo and hi index (why set lo = -1 ?)
We can use a Binary Search method to search for a particlar value in a sorted list. set the initial lo and hi index (why set lo = -1 ?) iv = index of current guess if guess too low drop 1st half of list if guess too high drop 2nd half if guess correct display and quit if not in list display message and quit
32
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.
33
Declaring Two-Dimensional Arrays
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 }, { 1, 1, 0 } }; As with one-dimensional arrays, you cannot change the size of a two-dimensional array once it has been declared.
34
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 row for (int j = 0; j < MEDALS; j++) // Process the jth column in the ith row System.out.printf("%8d", counts[i][j]); } System.out.println(); // Start a new line at the end of the row
35
Two-Dimensional Array Parameters
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 China Germany Korea Japan Russia USA
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.