24
Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Embed Size (px)

Citation preview

Page 1: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Chapter 11.Multidimensional Arrays

and Vectors Multidimensional Arrays Vectors

Computer Programming with JAVA

Page 2: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Overview

This chapter is a continuation of the previous one

If one-dimensional arrays are good, multi-dimensional arrays must be better

Vectors: arrays reconfigured as a class type

Page 3: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

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 (2-D) arrays

A 2-D 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

Page 4: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Table as a 2-D array

Balances for Various Interest RatesCompounded 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 $10752 $1103 $1113 $1124 $1134 $1145 $11563 $1158 $1174 $1191 $1208 $1225 $12424 $1216 $1239 $1262 $1286 $1311 $13355 $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

Chapter 11 Java: an Introduction to Computer Science & Programming - Walter Savitch 4

Page 5: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Table as a2-D array Indexes 0 1 2 3 4 5

0 $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)

Chapter 11 Java: an Introduction to Computer Science & Programming - Walter Savitch 5

Row Index 3(4th row)

Column Index 4(5th column)

Page 6: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

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];

Page 7: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

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 classInterestTable (excerpt fromDisplay 11.3/page 607):

Page 8: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

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 mainmethod ofInterestTable(Display 11.3/page 607):

Page 9: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

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(); } }

showTable method from class InterestTable2 (Display 11.5/page 614):

Notice how the numberof columns is obtained

Notice how the numberof rows is obtained

Page 10: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

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];

Page 11: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Vectors

"Well, I'll eat it," said Alice, "and if it makes me grow larger, I can reach the key; and if it makes me grow smaller, I can creep under the door; so either way I'll get into the garden…"

Lewis Carroll, Alice's Adventures in Wonderland

VECTORSThink of them as arrays that can get larger or

smallerwhen a program is running.

Page 12: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Arrays versus Vectors

ArraysBad: Size is fixed when declared Inefficient storage: can use a

partially full array, but space has been allocated for the full size

If one more value needs to be added past the maximum size the array needs to be redeclared

Good: More efficient (faster)

execution Allows primitive type elements

VectorsGood : Size is not fixed Better storage efficiency: a

partially full vector may be allocated just the space it needs

If one more value needs to be added past the maximum size the vector size increases automatically

Bad: Less efficient (slower)

execution Elements must be class types

(primitive types not allowed)

Page 13: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Using vectors

Vectors are not automatically part of Java they are in the util library you must import java.util.*

Create a vector with an initial size of 20 elements:Vector v = new Vector(20);

Page 14: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Initial capacity and efficiency:a classic engineering tradeoff

Engineering involves making difficult tradeoffs "There's no such thing as a free lunch."

• an American saying Usually, if you gain something you lose something

somewhere else

Choosing the initial size of a vector is an example of a tradeoff making it too large wastes allocated memory space making it too small slows execution

• it takes time to resize vectors dynamically

Solution? optimize one at the expense of the other or make good compromises

• choose a size that is not too big and not too small

Page 15: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Vector syntax The idea is the same as for arrays, but the syntax is different As with arrays, the index must be in the range 0 to size-of-the-vector

Array: a is a String array

a[i] = "Hi, Mom!");

String temp = a[i];

Vector: v is a vector

v.setElementAt("Hi, Mom!", i);

String temp = (String)v.elementAt(i);

Instead of the index in brackets and = for assignment, use vector method setElementAt with two arguments, the value and the index

Use vector method elementAt(int index) to retrieve the value of an element

Note: the cast to String is required because the base type of vector elements is Object

Page 16: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Vector methods

The vector class includes many useful methods: constructors array-like methods, e.g. setElementAt & elementAt methods to add elements methods to remove elements search methods methods to work with the vector's size and capacity,

e.g. to find its size and check if it is empty a clone method to copy a vector

See Display 11.8/pages 624-6

Page 17: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

A little detail about setElementAt

"The devil's in the details."• an American engineering saying

Vectors put values in successive indexes addElement is used to put initial values in a vector new values can be added only at the next higher index

You cannot use setElemetAt to put a value at any index setElemetAt can be used to assign the value of an

indexed variable only if it has been previously assigned a value with addElement

Page 18: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Base type of vectors

The base type of an array is specified when the array is declared all elements of arrays must be of the same type

The base type of a vector is Object elements of a vector can be of any class type in fact, elements of a vector can be of different class types! to store primitive types in a vector they must be converted to a

corresponding wrapper class

Good Programming PracticeAlthough vectors allow elements in the same vector to be of

different class types, it is best not to have a mix of classes in the same vector -

• it is best to have all elements in a vector be the same class type.

Page 19: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Detail: one consequence of the base type of vectors being Object

The following code looks very reasonable but will produce an error saying that the class Object does not have a method named length:

Vector v = new Vector()String greeting = "Hi, Mom!";v.addElement(greeting);System.out.println("Length is " + (v.elementAt(0)).length());

String, of course, does have a length method, but Java sees the type of v.elementAt(0) as Object, not String

Solution? Cast v.elementAt(0) to String:System.out.println

("Length is " + (String)(v.elementAt(0)).length());

Page 20: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

One more detail: size versus capacity Be sure to understand the difference between capacity

and size of a vector: capacity is the declared size of the vector

• the current maximum number of elements size is the actual number of elements being used

• the number of elements that contain valid values, not garbage

• remember that vectors add values only in successive indexes

Loops that read vector elements should be limited by the value of size, not capacity, to avoid reading garbage values

Page 21: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Programming tip:increasing storage efficiency of vectors A vector automatically increases its size if elements

beyond its current capacity are added

But a vector does not automatically decrease its size if elements are deleted

The method trimSize shrinks the capacity of a vector to its current size so there is no extra, wasted space the allocated space is reduced to whatever is currently being

used

To use storage more efficiently, use trimSize when a vector will not need its extra capacity later

Page 22: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

And another detail:correcting the return type of clone The method clone is used to make a copy of a

vector but its return type is Object, not Vector of course you want it be Vector, not Object

So, what do you do? Cast it to VectorVector v = new Vector(10);

Vector otherV;

otherV = vector;

Vector otherV = (Vector)v.clone();

This just makes otherV another name for the vector v

(there is only one copy of the vector and it now has two names)

This creates a second copy of v with a different name, otherV

Page 23: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

And yet another detail:protecting private variables Just as with arrays, be careful not to return addresses of

private vector variables, otherwise calling methods can access them directly "Information Hiding" is compromised

To protect against it, return a copy of the vector use clone as described in the previous slide

But that's not all: if the elements of the vector are class (and not primitive)

types, they may not have been written to pass a copy they may pass the address so additional work may be required to fix the accessor

methods

Page 24: Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA

Summary 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. Vectors can be thought of as arrays that can grow in length as

needed during run time. The base type of all vectors is Object. Thus, vector elements can be of any class type, but not

primitive types.