Java Programming Fourth Edition - Rutgers Universityszhou/351/ch08.pdfJava Programming, Fourth...

Preview:

Citation preview

Java Programming Fourth Edition

Chapter 8 Arrays

Java Programming, Fourth Edition 2

Objectives

•  Declare and initialize an array •  Use subscripts with an array •  Declare an array of objects •  Search an array for an exact match •  Search an array for a range match

Java Programming, Fourth Edition 3

Objectives (continued)

•  Pass arrays to methods •  Create arrays of Strings •  Sort array elements •  Use two-dimensional and multidimensional arrays •  Use the Arrays class

Java Programming, Fourth Edition 4

Declaring and Initializing an Array

•  Array –  Named list of data items –  All have same type

•  Declare array variable –  Same way as declaring any simple variable –  Insert pair of square brackets after type

Java Programming, Fourth Edition 5

Declaring and Initializing an Array (continued)

•  double[] salesFigure; •  int[] idNum; •  Still need to reserve memory space

–  salesFigure = new double[20]; –  double[] salesFigure = new double[20];

•  Subscript –  Integer contained within square brackets –  Indicates one of array’s variables or elements

Java Programming, Fourth Edition 6

Declaring and Initializing an Array (continued)

•  Array’s elements numbered beginning with zero –  Can legally use any subscript from 0 through 19 –  When working with array that has 20 elements

•  Work with any individual array element –  Treat no differently than single variable of same type –  salesFigure[0] = 2100.00;

Java Programming, Fourth Edition 7

An Array of 20 salesFigure Items in Memory

Java Programming, Fourth Edition 8

Initializing an Array

•  Variable with reference type –  Such as array –  Holds memory address where value stored

•  Array names –  Represent computer memory addresses –  Contain references

•  Declare array name –  No computer memory address assigned –  Has special value null

•  Unicode value ‘\u0000’

Java Programming, Fourth Edition 9

Initializing an Array (continued)

•  Use keyword new to define array –  Array name acquires actual memory address value

•  int[] someNums = new int[10]; –  Each element of someNums has value of 0

•  char array elements –  Assigned ‘\u0000’

•  boolean array elements –  Automatically assigned value false

Java Programming, Fourth Edition 10

Initializing an Array (continued)

•  Assign nondefault values to array elements upon creation –  int[] tenMult = {10, 20, 30, 40, 50, 60};

Java Programming, Fourth Edition 11

Using Subscripts with an Array

•  Scalar –  Primitive variable

•  Power of arrays –  Use subscripts that are variables –  Rather than constant subscripts –  Use a loop to perform array operations for (sub = 0; sub < 5; ++sub)

scoreArray[sub] += 3;

Java Programming, Fourth Edition 12

Using Subscripts with an Array (continued)

•  Application contains array –  Use every element of array in some task –  Perform loops that vary loop control variable

•  Start at 0 •  End at one less than size of array

•  Convenient to declare symbolic constant equal to size of array –  final int NUMBER_OF_SCORES = 5;

Java Programming, Fourth Edition 13

Using Subscripts with an Array (continued)

•  Field –  Instance variable –  Automatically assigned value for every array created

•  length field –  Contains number of elements in array for(sub = 0; sub < scoreArray.length; ++sub) scoreArray[sub] += 3;

Java Programming, Fourth Edition 14

Using Subscripts with an Array (continued)

•  Enhanced for loop –  Cycle through array –  Without specifying starting and ending points for loop

control variable for(int val : scoreArray)

System.out.println(val);

Java Programming, Fourth Edition 15

Declaring an Array of Objects

•  Create array of Employee objects –  Employee[] emp = new Employee[7]; –  Must call seven individual constructors final double PAYRATE = 6.35;

for(int x = 0; x < NUM_EMPLOYEES; ++x) emp[x] = new Employee(101 + x, PAYRATE);

Java Programming, Fourth Edition 16

Searching an Array For an Exact Match

•  Determine whether variable holds one of many valid values –  Use series of if statements –  Compare variable to series of valid values

Java Programming, Fourth Edition 17

Searching an Array For an Exact Match (continued)

•  Searching array –  Compare variable to list of values in array for(int x = 0; x < validValues.length; ++x)

{ if(itemOrdered == validValues[x])

– validItem = true; }

Java Programming, Fourth Edition 18

A for Loop with an Early Exit

Java Programming, Fourth Edition 19

Searching an Array For an Exact Match (continued)

•  Parallel array –  One with same number of elements as another –  Values in corresponding elements related

•  Alternative for searching –  Use while loop

Java Programming, Fourth Edition 20

A while Loop with an Early Exit

Java Programming, Fourth Edition 21

Searching an Array For a Range Match

•  Searching array for exact match –  Not always practical

•  Range match –  Compare value to endpoints of numerical ranges –  Find category in which value belongs

Java Programming, Fourth Edition 22

The FindDiscount Class

Java Programming, Fourth Edition 23

Passing Arrays to Methods

•  Pass single array element to method –  Same as passing variable

•  Passed by value –  Copy of value made and used in receiving method

•  Reference types –  Object holds memory address where values stored –  Receiving method gets copy of array’s actual

memory address

Java Programming, Fourth Edition 24

Passing Arrays to Methods (continued)

•  Reference types (continued) –  Receiving method has ability to alter original values

in array elements

Java Programming, Fourth Edition 25

The PassArrayElement Class

Java Programming, Fourth Edition 26

Creating Arrays of Strings

•  Create array of Strings String[] deptName = {"Accounting", "Human Resources", "Sales"};

for(int a = 0; a < deptName.length; ++a) System.out.println(deptName[a]);

Java Programming, Fourth Edition 27

The SearchList Class

Java Programming, Fourth Edition 28

Sorting Array Elements

•  Sorting –  Process of arranging series of objects in some

logical order •  Ascending order

–  Begin with object that has lowest value •  Descending order

–  Start with object that has largest value

Java Programming, Fourth Edition 29

Sorting Array Elements (continued)

•  Simplest possible sort –  Involves two values that are out of order –  Swap two values temp = valA; // 16 goes to temp

valA = valB; // 2 goes to valA valB = temp; // 16 goes to valB

Java Programming, Fourth Edition 30

Sorting Array Elements (continued)

•  Bubble sort –  Continue to compare pairs of items

•  Swapping them if they are out of order –  Smallest items “bubble” to top of list –  Eventually creating sorted list

Java Programming, Fourth Edition 31

Ascending Bubble Sort of the someNums Array Elements

Java Programming, Fourth Edition 32

More Efficient Ascending Bubble Sort of the someNums Array Elements

Java Programming, Fourth Edition 33

Sorting Arrays of Objects

•  Sort arrays of objects –  Same way that you sort arrays of primitive types –  Major difference

•  Make comparison that determines whether to swap two array elements

•  Sort based on particular object field

Java Programming, Fourth Edition 34

Using Two-Dimensional and Multidimensional Arrays

•  One-dimensional or single-dimensional array –  Picture as column of values –  Elements accessed using single subscript

•  Two-dimensional arrays –  Two or more columns of values –  Rows and columns –  Use two subscripts –  Matrix or table int[][] someNumbers = new int[3][4];

Java Programming, Fourth Edition 35

View of a Two-Dimensional Array in Memory

Java Programming, Fourth Edition 36

Using Two-Dimensional and Multidimensional Arrays (continued) int[][] rents = { {400, 450, 510}, {500, 560, 630},

{625, 676, 740}, {1000, 1250, 1600} };

public static void displayScores(int[][]scoresArray)

Java Programming, Fourth Edition 37

Using Two-Dimensional and Multidimensional Arrays (continued)

•  Multidimensional arrays –  More than two dimensions

•  Create arrays of any size –  Keep track of order of variables needed as

subscripts –  Don’t exhaust computer’s memory

Java Programming, Fourth Edition 38

Using the Arrays Class

•  Arrays class –  Contains many useful methods for manipulating

arrays –  static methods

•  Use with class name •  Without instantiating Arrays object

–  binarySearch() method •  Convenient way to search through sorted lists of

values of various data types •  List must be in order

Java Programming, Fourth Edition 39

Useful Methods of the Arrays Class

Java Programming, Fourth Edition 40

You Do It

•  Creating and populating an array •  Initializing an array •  Using a for loop to access array elements •  Creating parallel arrays to eliminate nested if

statements •  Creating an application with an array of objects

Java Programming, Fourth Edition 41

You Do It (continued)

•  Creating an interactive application that creates an array of objects

•  Passing an array to a method •  Using Arrays class methods

Java Programming, Fourth Edition 42

Summary

•  Array –  Named list of data items –  All have same type

•  Array names –  Represent computer memory addresses

•  Shorten many array-based tasks –  Use variable as subscript

•  length field –  Contains number of elements in array

Java Programming, Fourth Edition 43

Summary (continued)

•  Search array to find match to value •  Perform range match •  Pass single array element to method •  Sorting

–  Process of arranging series of objects in some logical order

•  Two-dimensional arrays –  Both rows and columns

•  Arrays class

Recommended