chapter 6 1 l array basics l arrays in classes and methods l programming with arrays and classes l...
TRANSCRIPT
Chapter 6 1
Chapter 6
Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays **
** multidimensional arrays will befurther discussed in COMP123
Arrays
Chapter 6 2
What is an Array?
Array [in general programming]» a contiguous block of equally-sized memory blocks» each block is distinguished by an index, subscript,
element number, or location value (all mean the same thing)» all array elements are of the same type (primitive or class)» allow multiple values to be [sort of] referenced by on name
Arrays [in Java]» are older programming structures (list switch/case)» for multi-value storage, you are encouraged to use the
advanced Java classes: Lists, Collections, and Vectors
Arrays are treated like objects (reference variables), without the ADT complexity of being instances of classes
Chapter 6 3
Creating Arrays
General syntax for declaring an array:type[] array_name = new type[length];
Examples:int[] heights; // array ref. var. (null array)heights = new int[22]; // array of 22 ints
// array of 80 characterschar[] symbol = new char[80];
// array of 100 double valuesdouble[] reading = new double[100];
// array of 15 Shape objects Shape[] geometries = new Shape[15];
Chapter 6 4
Three Position for [ ] (Brackets)when used with Arrays
declaration—to indicate that reference variable is a reference to an array of a specific type» create an int array variable, but not an array!» int[] pressure;
creating (allocating in memory) a new array» pressure = new int[100];» int[] levels = new int[10];
indexing a specific element within an array» levels[3] = SavitchIn.readLineInt();» System.out.print("4th elem."+levels[3]);
Chapter 6 5
Array Terminology
temperature[n + 2]
temperature[n + 2]
temperature[n + 2]
temperature[n + 2] = 32;
array name: temperature
index (also called a subscript, location, or element number) - must be an int, - or an expression that evaluates to an int
indexed variable (also called element)- holds the value at the index position
The term "element" is usually interchangeable with the terms: index, array value, element location, and "array thing at index"
data value of the indexed variable- also called an element of the array
Chapter 6 6
Array Length
length of an array defined during the: new type[length] statement» determines the number of equally-size data blocks allocated for
the array elements» memory locations are allocated, whether or not elements are
explicitly given values
array length is stored the instance variable length,Species[] entry = new Species[20];System.out.println( entry.length ); // shows: 20
array length is established during the new and cannot be changed» although the array reference variable can be "pointed to" a new
memory address that identifies another array of smaller, or larger, length! (more on this later)
Chapter 6 7
Initializing an Array during Declaration
arrays can be initialised during declaration with a comma-separated list in braces
non- initialised elements are assigned the default value,» 0 for numeric arrays, an activated constructor for objects» if only the list is provided, the array is of that length
example:double[] reading = {5.1, 3.02, 9.65};System.out.println( reading.length );
- displays "3", since array reading has values:[0] = 5.1[1] = 3.02[2] = 9.65
Chapter 6 8
Subscript Range
array indexes (subscripts) begin at [0] and proceed to [array length-1]» this is similar to character positions in String objects,
since String objects use characters arrays to store data
int[] scores = {97, 86, 92, 71};– in place of,
int[] scores = new int[4];scores[0] = 97;scores[1] = 86;scores[2] = 92;scores[3] = 71;
*** if reference is made beyond the [length-1] index, this generates a run-time error: "array subscript out of range"» Java is "array safe"—in C/C++, no error is reported!
Chapter 6 9
Initializing Array Elements with a Loop
since arrays are contiguous and of an unchanging size,a for loop is commonly used
array elements of numeric type are initialised to zero (0) during declaration
– elements of class type are initialised to null– it is always good to initialise an newly declared array—why?
example:int i; //loop counter/array indexint[] a = new int[10]; // 10 elem. int array
for(i=0; i<a.length; i++) // loop: 0..9 a[i] = 0; // init. to 0
Chapter 6 10
Some things to do with arrays setting element values to result of method call:
for (int i=0; i<ray.length; i++) { System.out.print("Enter value "+i+":"); ray[i] = SavitchIn.readLineInt();}
summing values in an array:for (int i=0; i<ray.length; i++) sum = sum + ray[i];
copy one array to another (both of equal length) :for (int i=0; i<array.length; i++) brray[i] = array[i];
reverse copy of one array to another (both of equal length) : for (int i=0; i<array.length; i++) { upperindex = (array.length-1)-i brray[i] = array[upperindex]; }or
for (int i=0, k=array.length-1; i<array.length; i++, k--) brray[i] = array[k];
Chapter 6 11
Some things to do with arrays determine the minimum and maximum values within an array
double min=ray[0], // init. both min and max max=ray[0]; // to the first element valuefor (int i=1; i<ray.length; i++) { if (ray[i] < min) // if current element < min min = ray[i]; // set min to current element if (ray[i] > max) // if current element > max max = ray[i]; // set max to current element}
for the above, could the second if be changed to else if ?
search for the first occurrence of a value & remember location:int loc = 0; // init. loc to first positionfor(loc=0; ((loc<ray.length) && (ray[loc]!=searchval)); loc++);
// after, if loc is < ray.length, item found at loc// if loc is = ray.length, item not found
Chapter 6 12
Some things to do with arrays check to see if two arrays are equal (same order of values):
boolean equal=true; // assume they are equalfor (int i=0; i<array.length; i++) { if (array[i] != brray[i]) // check if != { equal = false; // set false break; // stop loop }}
or
boolean equal=true; // assume they are equalfor (int i=0; equal ; i++) // loop while equal equal = (array[i] == brray[i]); // check equality
Chapter 6 13
Arrays and Array Elementsas Method Arguments
arrays, and the individual array elements, can be used with classes and methods just like other primitive variable and objects» both an indexed element and the array identifier can be
legally used as argument in a method call
through a return statement, methods can return a single array element value, or an array identifier
BUT DO NOT CONFUSE THE ARRAY WITH ITS ELEMENTS!!!» double[] list = new list[100];» list is not the same as list[2] !!!» list is an array reference, list[2] is a double variable value
Chapter 6 14
Array Names as Method Arguments
arrays are similar to objects: the array is a reference variable arrays arguments given to methods are pass-by-reference
» only the memory address is passed to the method» changes to the array in the method, change the original values
public static void getArray (int[] array){ for(int i = 0; i < array.length; i++) array[i] = inputInt("Enter value "+(i+1));}// end of getArray()
public static void showArray (int[] array){ for(int i = 0; i < array.length; i++) print( array[i] );}// end of showArray()
Chapter 6 15
Checking Arrays for Equality…in a Method
same technique as previous, except now using a method(remember: arrays must be of equal length)
public static boolean arrayEquals (double[] a, double[] b){ boolean equal=true; // assume they are equal
for (int i=0; i<a.length; i++) if (a[i] != b[i]) // check if != { equal = false; // set false break; // stop loop }
return (equal); // return equality status}// end of arrayEquals()
Chapter 6 16
Methods that Return an Array
an array is not passed in, but the address of the array is passed back
the local array name c (in main() ) is assigned the address which is returned from the call to vowels()
the local array in vowels(), newarray, is lost when the methods finishes but the address is returned and stored
Java reused memory only when nothing points to it!
public class returnArrayDemo { public static void main(String arg[]) { char[] c; c = vowels(); for(int i = 0; i < c.length; i++) System.out.println(c[i]); }// end of main() public static char[] vowels() { char[] newArray = new char[5]; newArray[0] = 'a'; newArray[0] = 'e'; newArray[0] = 'i'; newArray[0] = 'o'; newArray[0] = 'u'; return newArray; }// end of vowels() }// end of class returnArrayDemo
c, newArray, and the return type of vowels are all the same type: array of char
Chapter 6 17
Partially Filled Arrays
sometimes only part of an array contains useful data– consider an array of maximum 100 marks, but there are only
30 students in the class array elements always contain a value (random or otherwise)
a partially-filled array is a standard array, except that an int is declared to describe the number of used array elements
example:double[] quizzes = double [100]; // 100 quizzesint num_quizzes = 0; // hold # of quizzes
Chapter 6 18
Example of a Partially Filled Array
quizzes[0] 10.5
quizzes[1] 20.0
quizzes[2] 18.5
quizzes[3]
quizzes[4]
num_quizzes - 1
unused values
num_quizzes will have a value of 3
quizzes.length will have a value of 5
Chapter 6 19
Sorting an Array
sorting a list of elements is a common task with arrays– sort values in ascending order (1,2,4,10,12,20,...)– sort values in descending order (20,12,10,4,2,1,...)– sort strings in alphabetic order ("Bob", "Chuck", "Erin",...)
there are many techniques used in sorting» bubble sort, selection sort, shell sort, binary sort, quick sort, …
Selection sort (page 423)» easy to understand and program, although not efficient
Bubble sort (not in text)» also easy to understand and program, very inefficient
"the more efficient a sort technique is,the more difficult it is to understand!"
Chapter 6 20
Bubble Sort Algorithm
this technique processes an array multiple times and "percolates" (or bubbles) the largest value to the end of the array
– "largest to end"—ascending; "smallest to end"—descending– problem with bubble sort: it performs unnecessary sorts
the algorithm (ascending sort):1. assume the array is filled with out of order element values2. loop a counter i from the last element index down to 1
(i essentially works down the list, placing the largest at end)2.1 loop a counter j from 0 up to i
(j essentially works up the "unsorted" elements, pushing elements up)2.1.1 if current element (at [j]) is greater than next (at [j+1])
2.1.1.1 swap the element values between [j] and [j+1]3. end of sort, elements are now in sorted order
Chapter 6 21
public void bubblesort (int[] ray){ for (int i=ray.length-1; i>=1; i--) // loop last index down to 1
for (int j=0; j<i; j++) // loop 0 up to ith element if (ray[j] > ray[j+1]) // if cur. (j) > next (j+1), then swap (ray, j, j+1) // swap element, put in correct order // nothing to return, since the array is call-by-reference}// end of bubblesort()
public void swap (int array[], int pos1, int pos2){ int t; // internal dummary/temporary variable t = array[pos1]; // store value @ pos1 to t array[pos1] = array[pos2]; // store value @ pos2 to pos1 array[pos2] = t; // store t to pos2}// end of swap()
of course, whether the methods are public static void, or public void, or private void, depends on whether they are
– in a program class or utility class– public methods in a proper class, or – private methods used only within a class
Chapter 6 22
Multidimensional Arrays
arrays with more than one index» number of dimensions = number of indexes
arrays with more than two dimensions are a simple extension of two-dimensional (2D) arrays
a 2D array corresponds to a table or grid» one dimension is the row» the other dimension is the column» cell: an intersection of a row and column» an array element corresponds to a cell in the table
2D arrays are actually, 1D arrays in which each element is simply another 1D!
Chapter 6 23
Table as a 2-Dimensional Array
Balances for Various Interest Rates Compounded Annually
(Rounded to Whole Dollar Amounts) Year 5.00% 5.50% 6.00% 6.50% 7.00% 7.50%
1 $1050 $1055 $1060 $1065 $1070 $1075 2 $1103 $1113 $1124 $1134 $1145 $1156 3 $1158 $1174 $1191 $1208 $1225 $1242 4 $1216 $1239 $1262 $1286 $1311 $1335 5 $1276 $1307 $1338 $1370 $1403 $1436 … … … … … … …
The table assumes a starting balance of $1000 First dimension: row identifier - Year Second dimension: column identifier - percentage Cell contains balance for the year (row) and percentage (column) Balance for year 4, rate 7.00% = $1311
23
Table as a 2-D Array
Indexes 0 1 2 3 4 50 $1050 $1055 $1060 $1065 $1070 $10751 $1103 $1113 $1124 $1134 $1145 $11562 $1158 $1174 $1191 $1208 $1225 $12423 $1216 $1239 $1262 $1286 $1311 $13354 $1276 $1307 $1338 $1370 $1403 $1436… … … … … … …
Generalizing to two indexes: [row][column] First dimension: row index Second dimension: column index Cell contains balance for the year/row and percentage/column All indexes use zero-numbering
» Balance[3][4] = cell in 4th row (year = 4) and 5th column (7.50%)
» Balance[3][4] = $1311 (shown in yellow)24
Row Index 3(4th row)
Column Index 4(5th column)
Chapter 6 25
Java Code to Create a 2-D Array
Syntax for 2-D arrays is similar to 1-D arrays
Declare a 2-D array of ints named table» the table should have ten rows and six columns int[][] table = new int[10][6];
Chapter 6 26
Method to Calculate the Cell Values
Each array element corresponds to the balance for a specific number of years and a specific interest rate (assuming a startingbalance of $1000):
balance(starting, years, rate) = (starting) x (1 + rate)years
The repeated multiplication by (1 + rate) can be done in a for loop that repeats years times.
public static int balance(double startBalance, int years, double rate) { double runningBalance = startBalance; int count; for (count = 1; count <= years; count++) runningBalance = runningBalance*(1 + rate/100); return (int) (Math.round(runningBalance)); }
balance method in class InterestTable
Chapter 6 27
Processing a 2-D Array:for Loops Nested 2-Deep
Arrays and for loops are a natural fit To process all elements of an n-D array nest n for loops
» each loop has its own counter that corresponds to an index For example: calculate and enter balances in the interest table
» inner loop repeats 6 times (six rates) for every outer loop iteration
» the outer loop repeats 10 times (10 different values of years)
» so the inner repeats 10 x 6 = 60 times = # cells in table
int[][] table = new int[10][6]; int row, column; for (row = 0; row < 10; row++) for (column = 0; column < 6; column++) table[row][column] = balance(1000.00, row + 1, (5 + 0.5*column));
Excerpt from main() of InterestTable
Chapter 6 28
Multidimensional Array Parametersand Returned Values
Methods may have multi-D array parameters Methods may return a multi-D array as the value returned The situation is similar to 1-D arrays, but with more brackets Example: a 2-D int array as a method argument
public static void showTable(int[][] displayArray) { int row, column; for (row = 0; row < displayArray.length; row++) { System.out.print((row + 1) + " "); for (column = 0; column < displayArray[row].length; column++) System.out.print("$" + displayArray[row][column] + " "); System.out.println(); } }
Notice how the numberof columns is obtained
Notice how the numberof rows is obtained
showTable method from class InterestTable2
Chapter 6 29
Ragged Arrays
Ragged arrays have rows of unequal length» each row has a different number of columns, or entries
Ragged arrays are allowed in Java
Example: create a 2-D int array named b with 5 elements in the first row, 7 in the second row, and 4 in the third row:int[][] b;b = new int[3][];b[0] = new int[5];b[1] = new int[7];b[2] = new int[4];
Chapter 6 30
SummaryPart 1
An array may be thought of as a collection of variables, all of the same type.
An array is also may be thought of as a single object with a large composite value of all the elements of the array.
Arrays are objects created with new in a manner similar to objects discussed previously.
Chapter 6 31
SummaryPart 2
Array indexes use zero-numbering:» they start at 0, so index i refers to the(i+1)th element;» index of the last element: (length-of-the-array - 1)» Any index value outside the valid range of 0 to length-1 will
cause an array index out of bounds error when the program runs.
A method may return an array. A "partially filled array" is one in which values are stored in an
initial segment of the array:» use an int variable to keep track of how many variables
are stored.
Chapter 6 32
SummaryPart 3
An array indexed variable can be used as an argument to a method anyplace the base type is allowed:» if the base type is a primitive type then the method cannot
change the value of the indexed variable;» but if the base type is a class, then the method can change
the value of the indexed variable. When you want to store two or more different values (possibly of
different data types) for each index of an array, you can use parallel arrays (multiple arrays of the same length).
An accessor method that returns an array corresponding to a private instance variable of an array type should be careful to return a copy of the array, and not return the private instance variable itself.
The selection sort algorithm can be used to sort an array of numbers into increasing or decreasing order.
Chapter 6 33
SummaryPart 4
Arrays can have more than one index. Each index is called a dimension. Hence, multidimensional arrays have multiple indexes,
» e.g. an array with two indexes is a two-dimensional array. A two-dimensional array can be thought of as a grid or table
with rows and columns:» one index is for the row, the other for the column.
Multidimensional arrays in Java are implemented as arrays of arrays,» e.g. a two-dimensional array is a one-dimensional array of
one-dimensional arrays.