chapter 8 slides from gaddistext arrays of more than 1 dimension

30
Chapter 8 Chapter 8 Slides from Slides from GaddisText GaddisText Arrays of more than 1 Arrays of more than 1 dimension dimension

Upload: corey-bryan

Post on 19-Jan-2018

215 views

Category:

Documents


0 download

DESCRIPTION

Accessing Two-Dimensional Array Elements When processing the data in a two- dimensional array, each element has two subscripts: When processing the data in a two- dimensional array, each element has two subscripts: one for its row and one for its row and another for its column. another for its column.

TRANSCRIPT

Page 1: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Chapter 8 Chapter 8 Slides from GaddisText Slides from GaddisText

Arrays of more than 1 dimensionArrays of more than 1 dimension

Page 2: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Declaring a two-dimensional array requires two sets of Declaring a two-dimensional array requires two sets of brackets and two size declaratorsbrackets and two size declarators The first one is for the number of rowsThe first one is for the number of rows The second one is for the number of columns.The second one is for the number of columns.

double[][] scores = new double[3][4];double[][] scores = new double[3][4];

The two sets of brackets in the data type indicate that the The two sets of brackets in the data type indicate that the scores variable will reference a two-dimensional array. scores variable will reference a two-dimensional array.

Notice that each size declarator is enclosed in its own set Notice that each size declarator is enclosed in its own set of brackets.of brackets.

Two-Dimensional ArraysTwo-Dimensional Arrays

two dimensional array rows columns

Page 3: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Accessing Two-Dimensional Accessing Two-Dimensional Array ElementsArray Elements

When processing the data in a two-When processing the data in a two-dimensional array, each element has two dimensional array, each element has two subscripts:subscripts: one for its row and one for its row and another for its column.another for its column.

Page 4: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Accessing Two-Dimensional Accessing Two-Dimensional Array ElementsArray Elements

scores[0][3]scores[0][2]scores[0][1]scores[0][0]row 0

column 1 column 2 column 3column 0

row 1

row 2

The scores variableholds the address of a2D array of doubles.

Address

scores[1][3]scores[1][2]scores[1][1]scores[1][0]

scores[2][3]scores[2][2]scores[2][1]scores[2][0]

Page 5: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Accessing Two-Dimensional Accessing Two-Dimensional Array ElementsArray Elements

Accessing one of the elements in a two-dimensional array requires the use of both subscripts.

scores[2][1] = 95;

0000row 0

column 1 column 2 column 3column 0

row 1

row 2

Address

0000

00950

The scores variableholds the address of a2D array of doubles.

Page 6: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Accessing Two-Dimensional Accessing Two-Dimensional Array ElementsArray Elements

Programs that process two-dimensional arrays Programs that process two-dimensional arrays can do so with nested loops.can do so with nested loops.

To fill the scores array:To fill the scores array:for (int row = 0; row < 3; row++)for (int row = 0; row < 3; row++){{ for (int col = 0; col < 4; col++)for (int col = 0; col < 4; col++){{

System.out.print("Enter a score: ");System.out.print("Enter a score: "); scores[row][col] = keyboard.nextDouble();scores[row][col] = keyboard.nextDouble(); }}}}

Number of rows, not the largest subscript

Number of columns, not the largest subscript

keyboard references a Scanner object

Page 7: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Accessing Two-Dimensional Accessing Two-Dimensional Array ElementsArray Elements

To print out the To print out the scoresscores array: array:for (int row = 0; row < 3; row++)for (int row = 0; row < 3; row++){{ for (int col = 0; col < 4; col++)for (int col = 0; col < 4; col++){{

System.out.println(scores[row][col]);System.out.println(scores[row][col]); }}}}

See example: See example: CorpSales.javaCorpSales.java

Page 8: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Initializing a Two-Dimensional Initializing a Two-Dimensional ArrayArray

Initializing a two-dimensional array requires Initializing a two-dimensional array requires enclosing each row’s initialization list in its own set enclosing each row’s initialization list in its own set of braces.of braces.int[][] numbers = { int[][] numbers = { {{1, 2, 31, 2, 3}}, , {{4, 5, 64, 5, 6}}, , {{7, 8, 97, 8, 9}} };};

Java automatically creates the array and fills its Java automatically creates the array and fills its elements with the initialization values.elements with the initialization values. row 0 {1, 2, 3}row 0 {1, 2, 3} row 1 {4, 5, 6}row 1 {4, 5, 6} row 2 {7, 8, 9}row 2 {7, 8, 9}

Declares an array with three rows and three columns.Declares an array with three rows and three columns.

Page 9: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Initializing a Two-Dimensional Initializing a Two-Dimensional ArrayArray

321row 0

column 1 column 2column 0

row 1

row 2

Address

654

987

The numbers variableholds the address of a2D array of int values.

int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

produces:

Page 10: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

The The lengthlength Field Field Two-dimensional arrays are arrays of one-Two-dimensional arrays are arrays of one-

dimensional arrays.dimensional arrays. The length field of the array gives the number The length field of the array gives the number

of rows in the array. of rows in the array. Each row has a length constant tells how many Each row has a length constant tells how many

columns is in that row.columns is in that row. Each row can have a different number of Each row can have a different number of

columns.columns.

Page 11: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

The The lengthlength Field Field To access the To access the lengthlength fields of the array: fields of the array:

int[][] numbers = { { 1, 2, 3, 4 },int[][] numbers = { { 1, 2, 3, 4 }, { 5, 6, 7 },{ 5, 6, 7 }, { 9, 10, 11, 12 } };{ 9, 10, 11, 12 } };

for (int row = 0; row < for (int row = 0; row < numbers.lengthnumbers.length; row++); row++){{ for (int col = 0; col < for (int col = 0; col < numbers[row].lengthnumbers[row].length; col++); col++) System.out.println(numbers[row][col]);System.out.println(numbers[row][col]);}}

See example: See example: Lengths.javaLengths.javaNumber of rows Number of columns in this row.

The array can have variable length rows.

Page 12: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Summing The Elements of a Summing The Elements of a Two-Dimensional ArrayTwo-Dimensional Array

int[][] numbers = { { 1, 2, 3, 4 },int[][] numbers = { { 1, 2, 3, 4 }, {5, 6, 7, 8},{5, 6, 7, 8}, {9, 10, 11, 12} };{9, 10, 11, 12} };int total;int total;total = 0;total = 0;for (int row = 0; row < numbers.length; row++)for (int row = 0; row < numbers.length; row++){{ for (int col = 0; col < numbers[row].length; col++)for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col];total += numbers[row][col];}}

System.out.println("The total is " + total);System.out.println("The total is " + total);

Page 13: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Summing The Rows of a Two-Summing The Rows of a Two-Dimensional ArrayDimensional Array

int[][] numbers = {{ 1, 2, 3, 4},int[][] numbers = {{ 1, 2, 3, 4}, {5, 6, 7, 8},{5, 6, 7, 8}, {9, 10, 11, 12}};{9, 10, 11, 12}};int total;int total;

for (int for (int row row = 0; = 0; rowrow < numbers.length; < numbers.length; row row++)++){{ total = 0;total = 0; for (int for (int colcol = 0; = 0; colcol < numbers[row].length; < numbers[row].length; colcol++)++) total += numbers[row][col];total += numbers[row][col]; System.out.println("Total of row " System.out.println("Total of row " + row + " is " + total);+ row + " is " + total);}}

Page 14: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Summing The Columns of a Summing The Columns of a Two-Dimensional ArrayTwo-Dimensional Array

int[][] numbers = {{1, 2, 3, 4},int[][] numbers = {{1, 2, 3, 4}, {5, 6, 7, 8},{5, 6, 7, 8}, {9, 10, 11, 12}};{9, 10, 11, 12}};int total;int total;

for (int for (int colcol = 0; = 0; colcol < numbers[0].length; < numbers[0].length; colcol++)++){{ total = 0;total = 0; for (int for (int rowrow = 0; = 0; rowrow < numbers.length; < numbers.length; rowrow++)++) total += numbers[row][col];total += numbers[row][col]; System.out.println("Total of column " System.out.println("Total of column " + col + " is " + total);+ col + " is " + total);}}

Page 15: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Passing and Returning Two-Passing and Returning Two-Dimensional Array ReferencesDimensional Array References There is no difference between passing a There is no difference between passing a

single or two-dimensional array as an single or two-dimensional array as an argument to a method.argument to a method.

The method must accept a two-dimensional The method must accept a two-dimensional array as a parameter.array as a parameter.

See example: See example: Pass2Darray.javaPass2Darray.java

Page 16: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Ragged ArraysRagged Arrays When the rows of a two-dimensional array are of When the rows of a two-dimensional array are of

different lengths, the array is known as a different lengths, the array is known as a raggedragged arrayarray..

You can create a ragged array by creating a two-You can create a ragged array by creating a two-dimensional array with a specific number of rows, dimensional array with a specific number of rows, but no columns.but no columns.int [][] ragged = new int [4][];int [][] ragged = new int [4][];

Then create the individual rows.Then create the individual rows.ragged[0] = new int [3];ragged[0] = new int [3];ragged[1] = new int [4];ragged[1] = new int [4];ragged[2] = new int [5];ragged[2] = new int [5];ragged[3] = new int [6];ragged[3] = new int [6];

Page 17: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

More Than Two DimensionsMore Than Two Dimensions Java does not limit the number of dimensions that an Java does not limit the number of dimensions that an

array may be.array may be. More than three dimensions is hard to visualize, but More than three dimensions is hard to visualize, but

can be useful in some programming problems.can be useful in some programming problems.

Page 18: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Selection SortSelection Sort In a selection sort:In a selection sort:

The smallest value in the array is located and The smallest value in the array is located and moved to element 0.moved to element 0.

Then the next smallest value is located and moved Then the next smallest value is located and moved to element 1.to element 1.

This process continues until all of the elements This process continues until all of the elements have been placed in their proper order.have been placed in their proper order.

See example: See example: SelectionSortDemo.javaSelectionSortDemo.java

Page 19: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Binary SearchBinary Search A binary search:A binary search:

requires an array sorted in ascending order.requires an array sorted in ascending order. starts with the element in the middle of the array.starts with the element in the middle of the array. If that element is the desired value, the search is over.If that element is the desired value, the search is over. Otherwise, the value in the middle element is either Otherwise, the value in the middle element is either

greater or less than the desired valuegreater or less than the desired value If it is greater than the desired value, search in the first If it is greater than the desired value, search in the first

half of the array.half of the array. Otherwise, search the last half of the array.Otherwise, search the last half of the array. Repeat as needed while adjusting start and end points Repeat as needed while adjusting start and end points

of the search.of the search. See example: See example: BinarySearchDemo.javaBinarySearchDemo.java

Page 20: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Command-Line ArgumentsCommand-Line Arguments A Java program can receive arguments from the A Java program can receive arguments from the

operating system command-line.operating system command-line. The The mainmain method has a header that looks like this: method has a header that looks like this:

public static void main(String[] args)public static void main(String[] args) The main method receives a The main method receives a StringString array as a array as a

parameter.parameter. The array that is passed into the The array that is passed into the argsargs parameter parameter

comes from the operating system command-line.comes from the operating system command-line.

Page 21: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Command-Line ArgumentsCommand-Line Arguments To run the example:To run the example:

java CommandLine java CommandLine How does this work?How does this work?args[0] is assigned "How"args[0] is assigned "How"args[0] is assigned "does"args[0] is assigned "does"args[0] is assigned "this"args[0] is assigned "this"args[0] is assigned "work?"args[0] is assigned "work?"

Example: Example: CommandLine.javaCommandLine.java It is not required that the name of It is not required that the name of mainmain’s ’s

parameter array be parameter array be argsargs..

Page 22: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Variable-Length Argument ListsVariable-Length Argument Lists Special type parameter – vararg…Special type parameter – vararg…

Vararg parameters are actually arraysVararg parameters are actually arrays Examples: Examples: VarArgsDemo1.javaVarArgsDemo1.java, , VarargsDemo2.javaVarargsDemo2.java

public static int sum(int... numbers)public static int sum(int... numbers){{

int total = 0; // Accumulatorint total = 0; // Accumulator// Add all the values in the numbers array.// Add all the values in the numbers array.for (int val : numbers)for (int val : numbers)

total += val;total += val;// Return the total.// Return the total.return total;return total;

}}

Page 23: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

The The ArrayListArrayList Class Class Similar to an array, an Similar to an array, an ArrayListArrayList allows allows

object storageobject storage Unlike an array, an Unlike an array, an ArrayListArrayList object: object:

Automatically expands when a new item is addedAutomatically expands when a new item is added Automatically shrinks when items are removedAutomatically shrinks when items are removed

Requires: Requires: import java.util.ArrayList;import java.util.ArrayList;

Page 24: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Creating and Using an Creating and Using an ArrayListArrayList

Create an Create an ArrayListArrayList object with no-args object with no-args constructorconstructor ArrayList nameList = new ArrayList();ArrayList nameList = new ArrayList();

To populate the To populate the ArrayListArrayList, use the , use the addadd method:method: nameList.add("James");nameList.add("James"); nameList.add("Catherine");nameList.add("Catherine");

To get the current size, call the To get the current size, call the sizesize method method nameList.size(); nameList.size(); // returns 2// returns 2

Page 25: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Creating and Using an Creating and Using an ArrayListArrayList

To access items in an To access items in an ArrayListArrayList, use the , use the getget method methodnameList.get(1); nameList.get(1);

In this statement 1 is the index of the item to get.In this statement 1 is the index of the item to get.

Example: Example: ArrayListDemo1.javaArrayListDemo1.java

Page 26: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Using an Using an ArrayListArrayList The The ArrayListArrayList class's class's toStringtoString method r method returns a eturns a

string representing all items in the string representing all items in the ArrayListArrayListSystem.out.println(nameList);System.out.println(nameList);

This statement yields This statement yields ::[ James, Catherine ][ James, Catherine ]

The The ArrayListArrayList class's class's removeremove method removes method removes designated item from the designated item from the ArrayListArrayListnameList.remove(1); nameList.remove(1); This statement removes the second item.This statement removes the second item.

See example: See example: ArrayListDemo3.javaArrayListDemo3.java

Page 27: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Using an Using an ArrayListArrayList The The ArrayListArrayList class's class's addadd method with one method with one

argument adds new items to the end of the argument adds new items to the end of the ArrayListArrayList

To insert items at a location of choice, use the To insert items at a location of choice, use the addadd method with two arguments:method with two arguments:nameList.add(1, "Mary");nameList.add(1, "Mary");

This statement inserts the This statement inserts the StringString "Mary" at index 1 "Mary" at index 1 To replace an existing item, use the To replace an existing item, use the setset method: method:

nameList.set(1, "Becky"); nameList.set(1, "Becky"); This statement replaces “Mary” with “Becky”This statement replaces “Mary” with “Becky”

See example: See example: ArrayListDemo4.javaArrayListDemo4.java

Page 28: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Using an Using an ArrayListArrayList An ArrayList has a capacity, which is the number of An ArrayList has a capacity, which is the number of

items it can hold without increasing its size.items it can hold without increasing its size. The default capacity of an The default capacity of an ArrayListArrayList is 10 items. is 10 items. To designate a different capacity, use a To designate a different capacity, use a

parameterized constructor:parameterized constructor:ArrayList list = new ArrayList(100);ArrayList list = new ArrayList(100);

Page 29: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Using a Cast Operator with the Using a Cast Operator with the getget MethodMethod

An An ArrayListArrayList object is not typed object is not typed To retrieve items from an To retrieve items from an ArrayListArrayList, you , you

must cast the item to the appropriate typemust cast the item to the appropriate typeArrayList nameList = new ArrayList();ArrayList nameList = new ArrayList();

nameList.add("Mary"); // Inserts an itemnameList.add("Mary"); // Inserts an item String str = (String)nameList.get(0);String str = (String)nameList.get(0);

Try Try getget without the cast to see the effect. without the cast to see the effect. Example: Example: ArrayListDemo6.javaArrayListDemo6.java

Page 30: Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Using Using ArrayListArrayList as a Generic Data as a Generic Data TypeType

You can create a type-safe You can create a type-safe ArrayListArrayList object by object by using generics.using generics.

For example an For example an ArrayListArrayList object for object for StringStrings:s:ArrayList<String> nameList = new ArrayList<String>();ArrayList<String> nameList = new ArrayList<String>();

The The getget method no longer requires casts to work. method no longer requires casts to work. Example: Example: GenericArrayListDemo1.javaGenericArrayListDemo1.java Example: Example: GenericArrayListDemo2.javaGenericArrayListDemo2.java