Вы находитесь на странице: 1из 51

Java Programming Fifth Edition

Arrays

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, Fifth Edition

Objectives (continued)
Pass arrays to and return arrays from methods Manipulate arrays of Strings Sort array elements Use two-dimensional and multidimensional arrays Use the Arrays class Use the ArrayList class

Java Programming, Fifth Edition

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, Fifth Edition

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 arrays variables or elements

Java Programming, Fifth Edition

Declaring and Initializing an Array (continued)


Arrays 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 Example: salesFigure[0] = 2100.00;

Java Programming, Fifth Edition

Declaring and Initializing an Array (continued)

Java Programming, Fifth Edition

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, Fifth Edition 8

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, Fifth Edition

Initializing an Array (continued)


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

Java Programming, Fifth Edition

10

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, Fifth Edition

11

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, Fifth Edition

12

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, Fifth Edition

13

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, Fifth Edition

14

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, Fifth Edition

15

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, Fifth Edition

16

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, Fifth Edition

17

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, Fifth Edition

18

Java Programming, Fifth Edition

19

Searching an Array For an Exact Match (continued)

Java Programming, Fifth Edition

20

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, Fifth Edition

21

Java Programming, Fifth Edition

22

Passing Arrays to and Returning Arrays from Methods


Pass single array element to method
Same as passing variable

Passed by value
Copy of value made and used in receiving method All primitive types passed this way

Java Programming, Fifth Edition

23

Passing Arrays to Methods (continued)


Reference types
Object holds memory address where values stored Receiving method gets copy of arrays actual memory address Receiving method has ability to alter original values in array elements

Java Programming, Fifth Edition

24

Java Programming, Fifth Edition

25

Returning an Array from a Method


Method can return an array reference Include square brackets with the return type
In the method header

Java Programming, Fifth Edition

26

Manipulating 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, Fifth Edition

27

Manipulating Arrays of Strings (continued)

Java Programming, Fifth 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, Fifth 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, Fifth 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, Fifth Edition

31

Sorting Array Elements (continued)

Java Programming, Fifth Edition

32

Sorting Array Elements (continued)

Java Programming, Fifth 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, Fifth 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, Fifth Edition

35

Using Two-Dimensional and Multidimensional Arrays (continued)

Java Programming, Fifth 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, Fifth Edition

37

Using the length Field with a TwoDimensional Array


length field holds the number of rows in the array
rents.length

Each row has a length field that holds the number of columns in the row
rents[1].length

Java Programming, Fifth Edition

38

Understanding Ragged Arrays


Two-dimensional array with rows of different length Define the number of rows for a two-dimensional array
But not defining the number of columns in the rows

Then declare the individual rows

Java Programming, Fifth Edition

39

Using Multidimensional Arrays


Multidimensional arrays
More than two dimensions

Create arrays of any size


Keep track of order of variables needed as subscripts Dont exhaust computers memory

Java Programming, Fifth Edition

40

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, Fifth Edition 41

Using the Arrays Class (continued)

Java Programming, Fifth Edition

42

Using the ArrayList Class


Provides some advantages over the Arrays class
Dynamically resizable Can add an item at any point in an ArrayList container Can remove an item at any point in an ArrayList container

Capacity
Number of items ArrayList can hold without having to increase its size

Java Programming, Fifth Edition

43

Using the ArrayList Class (continued)

Java Programming, Fifth Edition

44

Understanding the Limitations of the ArrayList Class


Cannot use an ArrayList to store primitive types

Must cast elements to the appropriate reference type


Or you must declare a reference type in the ArrayList declaration

Java Programming, Fifth Edition

45

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, Fifth Edition

46

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, Fifth Edition

47

Dont Do It
Dont forget that the lowest array subscript is 0 Dont forget that the highest array subscript is one less than the length Dont forget that length is an array property and not a method Dont place a subscript after an objects field or method name when accessing an array of objects Dont forget that array names are references

Java Programming, Fifth Edition

48

Dont Do It (continued)
Dont use brackets with an array name when you pass it to a method Dont assume that an array of characters is a string Dont forget that the first subscript used with a twodimensional array represents the row, and that the second subscript represents the column

Java Programming, Fifth Edition

49

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, Fifth Edition 50

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 ArrayList class


Java Programming, Fifth Edition 51

Вам также может понравиться