jhtp10_ch06_Arrays

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 103

Java How to Program,

Late Objects Version, 10/e

©1992-2015 by Pearson Education, Inc. All Rights


Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Data structures—collections of related data items.
 Array objects—data structures consisting of related data items of
the same type.
◦ Make it convenient to process related groups of values.
◦ Remain the same length once they’re created.
 Enhanced for statement—allows a program to access the data
in an array more easily than does the counter-controlled for
statement.
 Use variable-length argument lists to create methods that can be
called with varying numbers of arguments.
 Demonstrate how to process command-line arguments in method
main.
 static methods of class Arrays from the java.util
package.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 At the end of this chapter, we introduce one of Java’s prebuilt
data structures from the Java API’s collection classes.
◦ Greater capabilities than traditional arrays.
◦ Reusable, reliable, powerful and efficient.
◦ Focus on the ArrayList collection.
 ArrayLists are similar to arrays but provide additional
functionality, such as dynamic resizing as necessary to
accommodate more or fewer elements.
 Java SE 8
◦ After reading Chapter 17, Java SE 8 Lambdas and Streams, you’ll be
able to reimplement many of Chapter 6’s examples in a more concise
and elegant manner, and in a way that makes them easier to parallelize
to improve performance on today’s multi-core systems.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Java’s types are divided into primitive types and
reference types.
◦ Primitive types: boolean, byte, char, short, int,
long, float and double.
 All nonprimitive types are reference types.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 A primitive-type variable can hold exactly one value of its
declared type at a time.
 Programs use variables of reference types (normally called
references) to store the addresses of objects in the
computer’s memory.
◦ Such a variable is said to refer to an object in the program.
 To call an object’s methods, you need a reference to the
object.
 If an object’s method requires additional data to perform its
task, then you’d pass arguments in the method call.
 Primitive-type variables do not refer to objects, so such
variables cannot be used to invoke methods.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 An array is a group of variables (called elements or
components) containing values that all have the same type.
 Arrays are objects, so they’re considered reference types.
 Elements can be either primitive types or reference types.
 To refer to a particular element in an array, we specify the
name of the reference to the array and the position number
of the element in the array.
◦ The position number of the element is called the element’s index or
subscript.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 A program refers to an array’s elements with an array-access
expression
◦ The name of the array followed by the index of the particular element in
square brackets ([]).
 The first element in every array has index zero and is sometimes
called the zeroth element.
 The highest index in an array is one less than the number of
elements.
 Array names follow the same conventions as other variable
names.
 An index must be a nonnegative integer.
 A program can use an expression as an index.
 Array-access expressions can be used on the left side of an
assignment to place a new value into an array element.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Every array object knows its own length and stores it in
a length instance variable.
 Even though the length instance variable of an array

is public, it cannot be changed because it’s a final


variable.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Like other objects, arrays are created with keyword new.
 To create an array object, you specify the type of the
array elements and the number of elements as part of an
array-creation expression that uses keyword new.
◦ Returns a reference that can be stored in an array
variable.
 The following declaration and array-creation expression
create an array object containing 12 int elements and
store the array’s reference in the array variable named c:
 int[] c = new int[12];
 The square brackets following the type indicate that the
variable will refer to an array.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 A program can declare arrays of any type.
 Every element of a primitive-type array contains a

value of the array’s declared element type.


 Similarly, in an array of a reference type, every element

is a reference to an object of the array’s declared


element type.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 This section presents several examples that
demonstrate declaring arrays, creating arrays,
initializing arrays and manipulating array elements.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 The application of Fig. 6.2 uses keyword new to create
an array of 10 int elements, which are initially zero
(the default initial value for int variables).

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 You can create an array and initialize its elements with an array
initializer—a comma-separated list of expressions (called an
initializer list) enclosed in braces.
 Tthe array length is determined by the number of elements in the
initializer list.
 The following statement creates a five-element array with index
values 0–4
int[] n = { 10, 20, 30, 40, 50 };
 Element n[0] is initialized to 10, n[1] is initialized to 20, and
so on.
 When the compiler encounters an array declaration that includes
an initializer list, it counts the number of initializers in the list to
determine the size of the array, then sets up the appropriate new
operation “behind the scenes.”

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 The application in Fig. 6.4 creates a 10-element array
and assigns to each element one of the even integers
from 2 to 20 (2, 4, 6, …, 20).
 Modifier final indicates that a variable is a
constant.
 Constant variables must be initialized before they’re
used and cannot be modified thereafter.
 If you attempt to modify a final variable after it’s
initialized in its declaration, the compiler issues an
error message like
 cannot assign a value to final variable
variableName

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Often, the elements of an array represent a series of
values to be used in a calculation.
 Figure 6.5 sums the values contained in a 10-element

integer array.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Many programs present data to users in a graphical
manner.
 For example, numeric values are often displayed as

bars in a bar chart.


 In such a chart, longer bars represent proportionally

larger numeric values.


 One simple way to display numeric data graphically is

with a bar chart that shows each numeric value as a bar


of asterisks (*).

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Sometimes, programs use counter variables to summarize
data, such as the results of a survey.
 In Fig. 5.7, we used separate counters in our die-rolling
program to track the number of occurrences of each side of
a six-sided die as the program rolled the die 6,000,000
times.
 An array version of this application is shown in Fig. 6.7.
 Figure 6.7 uses the array frequency to count the
occurrences of each side of the die.
 The single statement in line 14 of this program replaces
lines 22–45 of Fig. 5.7.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Our next example uses arrays to summarize data collected in a
survey:
◦ Twenty students were asked to rate on a scale of 1 to 5 the
quality of the food in the student cafeteria, with 1 being
“awful” and 5 being “excellent.” Place the 20 responses in
an integer array and determine the frequency of each rating.
 Typical array-processing application (Fig. 6.8).
 Summarize the number of responses of each type (that is, 1
through 5).
 Array responses is a 20-element integer array containing
the students’ survey responses.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 The last value in the array is intentionally an
incorrect response (14).
 When a Java program executes, array element indices
are checked for validity—all indices must be greater
than or equal to 0 and less than the length of the
array.
 Any attempt to access an element outside that range
of indices results in a runtime error that’s known as
an ArrayIndexOutOfBoundsException.
 We use the six-element array frequency to count
the number of occurrences of each response.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 The for statement (lines 15–27) reads the responses
from the responses one at a time and increments
one of the counters frequency[1] to
frequency[5]; we ignore frequency[0]
because the survey responses are limited to the range
1–5.
 The key statement in the loop appears in line 19.
 This statement increments the appropriate

frequency counter as determined by the value of


responses[answer].

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 An exception indicates a problem that occurs while a program
executes.
 Exception handling helps you create fault-tolerant programs
that can resolve (or handle) exceptions.
 In many cases, this allows a program to continue executing as
if no problems were encountered.
 More severe problems might prevent a program from
continuing normal execution, instead requiring the program to
notify the user of the problem, then terminate.
 When the JVM or a method detects a problem, such as an
invalid array index or an invalid method argument, it throws
an exception—that is, an exception occurs.
 Methods in your own classes can also throw exceptions, as
you’ll learn in Chapter 8.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 To handle an exception, place any code that might
throw an exception in a try statement.
 The try block contains the code that might throw an
exception, and the catch block contains the code
that handles the exception if one occurs.
 You can have many catch blocks to handle different
types of exceptions that might be thrown in the
corresponding try block.
 The braces that delimit the bodies of the try and
catch blocks are required.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 When the program encounters the invalid value 14 in the
responses array, it attempts to add 1 to
frequency[14], which is outside the bounds of the
array—the frequency array has only six elements (with
indexes 0–5).
 Because array bounds checking is performed at execution
time, the JVM generates an exception—specifically line
19 throws an
ArrayIndexOutOfBoundsException to notify
the program of this problem.
 At this point the try block terminates and the catch
block begins executing—any local variables declared in
the try block are now out of scope (and no longer exist),
so they’re not accessible in the catch block.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 When lines 21–26 catch the exception, the program
displays a message indicating the problem that occurred.
 Line 23 implicitly calls the exception object’s
toString method to get the error message that’s
implicitly stored in the exception object and display it.
 Once the message is displayed in this example, the
exception is considered handled and the program
continues with the next statement after the catch
block’s closing brace.
 In this example, the end of the for statement is reached
(line 27), so the program continues with the increment of
the control variable in line 15.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Iterates through the elements of an array without
using a counter, thus avoiding the possibility of
“stepping outside” the array.
 Syntax:
 for (parameter : arrayName)
statement
◦ where parameter has a type and an identifier, and
arrayName is the array through which to iterate.
◦ Parameter type must be consistent with the type of the
elements in the array.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Figure 6.9 uses the enhanced for statement to sum
the integers in an array of student grades.
 Can be used only to obtain array elements—it cannot
be used to modify elements.
 Can be used in place of the counter-controlled for
statement whenever code looping through an array
does not require access to the counter indicating the
index of the current array element.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 To pass an array argument to a method, specify the name
of the array without any brackets.
 When we pass an array object’s reference into a method,
we need not pass the array length as an additional
argument because every array knows its own length.
 For a method to receive an array reference through a
method call, the method’s parameter list must specify an
array parameter.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 When an argument to a method is an entire array or
an individual array element of a reference type, the
called method receives a copy of the reference.
 However, when an argument to a method is an
individual array element of a primitive type, the
called method receives a copy of the element’s value.
 Such primitive values are called scalars or scalar
quantities.
 To pass an individual array element to a method, use
the indexed name of the array element as an
argument in the method call.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Figure 6.10 demonstrates the difference between
passing an entire array and passing a primitive-type
array element to a method.
 Method modifyArray receives a copy of array’s

reference and uses the reference to multiply each of


array’s elements by 2.
 When a copy of an individual primitive-type array

element is passed to a method, modifying the copy in


the called method does not affect the original value of
that element in the calling method’s array.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Two ways to pass arguments in method calls in many
programming languages are pass-by-value and pass-by-
reference.
 When an argument is passed by value, a copy of the
argument’s value is passed to the called method.
◦ The called method works exclusively with the copy.
◦ Changes to the called method’s copy do not affect the original
variable’s value in the caller.
 When an argument is passed by reference, the called
method can access the argument’s value in the caller
directly and modify that data, if necessary.
◦ Improves performance by eliminating the need to copy possibly
large amounts of data.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Java does not allow you to choose pass-by-value or pass-by-
reference—all arguments are passed by value.
 A method call can pass two types of values to a method—
copies of primitive values and copies of references to
objects.
◦ Objects themselves cannot be passed to methods.
 If you modify a reference-type parameter so that it refers to
another object, only the parameter refers to the new.
 Although an object’s reference is passed by value, a method
can still interact with the referenced object by calling its
public methods using the copy of the object’s reference.
◦ The parameter in the called method and the argument in the calling
method refer to the same object in memory.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Multidimensional arrays with two dimensions are often
used to represent tables of values with data arranged in rows
and columns.
◦ To identify a particular table element, you specify two indices—the
first identifies the element’s row and the second its column.
 Arrays that require two indices to identify each element are
called two-dimensional arrays.
 Multidimensional arrays can have more than two
dimensions.
◦ Java does not support multidimensional arrays directly, but it allows
you to specify one-dimensional arrays whose elements are also one-
dimensional arrays, thus achieving the same effect.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Figure 6.11 illustrates a two-dimensional array named
a with three rows and four columns (i.e., a three-by-
four array).
 In general, an array with m rows and n columns is

called an m-by-n array.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Multidimensional arrays can be initialized with array initializers
in declarations.
 A two-dimensional array b with two rows and two columns
could be declared and initialized with nested array initializers as
follows:
 int[][] b = { { 1, 2 }, { 3, 4 } };
 The initial values are grouped by row in braces.
 The compiler counts the number of nested array initializers to
determine the number of rows in array b.
 The compiler counts the initializer values in the nested array
initializer for a row to determine the number of columns in that
row.
 Rows can have different lengths.
 Multidimensional arrays are maintained as arrays of one-
dimensional arrays.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 A multidimensional array with the same number of columns in
every row can be created with an array-creation expression, as in:
 int[][] b = new int[3][4];
 Programs can also use variables to specify array dimensions,
because new creates arrays at execution time—not at compile
time.
 The elements of a multidimensional array are initialized when the
array object is created.
 A multidimensional array in which each row has a different
number of columns can be created as follows:
 int[][] b = new int[2][ ]; // create 2 rows
b[0] = new int[5]; // create 5 columns for row 0
b[1] = new int[3]; // create 3 columns for row 1

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Figure 6.12 demonstrates initializing two-dimensional
arrays with array initializers, and using nested for
loops to traverse the arrays—that is, manipulate every
element of each array.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 With variable-length argument lists, you can create methods
that receive an unspecified number of arguments.
 A type followed by an ellipsis (...) in a method’s
parameter list indicates that the method receives a variable
number of arguments of that particular type.
◦ Can occur only once in a parameter list, and the ellipsis, together
with its type and the parameter name, must be placed at the end of
the parameter list.
 Figure 6.13 demonstrates method average which receives
a variable-length sequence of doubles.
 Java treats the variable-length argument list as an array
whose elements are all of the same type.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 It’s possible to pass arguments from the command line
to an application via method main’s String[]
parameter, which receives an array of Strings.
 By convention, this parameter is named args.
 When an application is executed using the java

command, Java passes the command-line arguments


that appear after the class name in the java command
to the application’s main method as Strings in the
array args.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Class Arrays helps you avoid reinventing the wheel by
providing static methods for common array manipulations.
 These methods include sort for sorting an array (i.e., arranging
elements into ascending order), binarySearch for searching
a sorted array (i.e., determining whether an array contains a
specific value and, if so, where the value is located), equals for
comparing arrays and fill for placing values into an array.
 These methods are overloaded for primitive-type arrays and for
arrays of objects.
 You can copy arrays with class System’s static
arraycopy method.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
Java SE 8—Class Arrays Method parallelSort
The Arrays class now has several new “parallel”
methods that take advantage of multi-core hardware.
Arrays method parallelSort can sort large
arrays more efficiently on multi-core systems.
In Section 23.12, we create a very large array and use
features of the Java SE 8 Date/Time API to compare
how long it takes to sort the array with methods sort
and parallelSort.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Collections provide efficient methods that organize, store
and retrieve your data without requiring knowledge of
how the data is being stored.
 The collection class ArrayList<T> (package
java.util) can dynamically change its size to
accommodate more elements.
 The T (by convention) is a placeholder—when declaring
a new ArrayList, replace it with the type of elements
that you want the ArrayList to hold.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Classes with this kind of placeholder that can be used
with any type are called generic classes.
 Figure 6.16 shows some common methods of class
ArrayList<T>.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Figure 6.17 demonstrates some common
ArrayList capabilities.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
Java SE 7—Diamond (<>) Notation for Creating an Object of
a Generic Class
Consider line 10 of Fig. 6.17:
 ArrayList<String> items = new ArrayList<String>();
ArrayList<String> appears in the variable declaration
and in the class instance creation expression. Java SE 7
introduced the diamond (<>) notation to simplify statements like
this.
Using <> in a class instance creation expression for an object
of a generic class tells the compiler to determine what belongs in
the angle brackets.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 In Java SE 7 and higher, the preceding statement can be
written as:
 ArrayList<String> items = new ArrayList<>();
 When the compiler encounters the diamond (<>) in the class
instance creation expression, it uses the declaration of variable
items to determine the ArrayList’s element type
(String)—this is known as inferring the element type.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Using Java’s graphics features, we can create complex
drawings that would be more tedious to code line by line.
 In Figs. 6.18-6.19, we use arrays and repetition statements
to draw a rainbow by using Graphics method fillArc.
 Drawing arcs in Java is similar to drawing ovals—an arc is
simply a section of an oval.
 The colors of a rainbow are red, orange, yellow, green, blue,
indigo and violet.
 Java has predefined constants only for the first five colors.
 Lines 15–17 initialize an array with the colors of the
rainbow, starting with the innermost arcs first.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 The fillArc method draws a filled arc.
 Method fillArc requires six parameters.
◦ The first four represent the bounding rectangle in which the arc will
be drawn.
◦ The first two of these specify the coordinates for the upper-left
corner of the bounding rectangle, and the next two specify its width
and height.
◦ The fifth parameter is the starting angle on the oval, and the sixth
specifies the sweep, or the amount of arc to cover.
◦ The starting angle and sweep are measured in degrees, with zero
degrees pointing right.
◦ A positive sweep draws the arc counterclockwise.
◦ Method drawArc requires the same parameters as fillArc, but
draws the edge of the arc rather than filling it.

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.

You might also like