Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 53

Java How to Program,

Late Objects Version, 10/e

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


 The content is mainly selected (sometimes modified)
from the original slides provided by the authors of the
textbook

 Readings
◦ Chapter 6: Arrays and ArrayLists
◦ Chapter 19: Searching, Sorting and Big O

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
6.1  Introduction
6.3  Arrays
6.4  Declaring and Creating Arrays
6.5  Examples Using Arrays
6.5.1 Creating and Initializing an Array
6.5.2 Using an Array Initializer
6.5.3 Calculating the Values to Store in an Array
6.5.4 Summing the Elements of an Array
6.7  Enhanced for Statement

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
6.8   Passing Arrays to Methods
6.10  Multidimensional Arrays
6.11  Variable-Length Argument Lists
6.12  Using Command-Line Arguments
6.13  Class Arrays
19.2  Linear Search

©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.
 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.
 Example of int array declaration and initialization:
◦ int[] c = new int[12];

©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
◦ Example: print the 6th element of the array:
 System.out.printlln(c[5]);
 The first element in every array has index zero: c[0]
 The highest index in an array (11) is one less than the
number of elements (12).
 Array names follow the same conventions as other
variable names (c, array2, intArray, etc.).
 An index must be a nonnegative integer (c[-3] not
allowed).

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 A program can use an expression as an index (c[i-j+1]).
 Array-access expressions can be used on the left side of
an assignment to place a new value into an array element.
◦ c[2] = 40;
 Every array object knows its own length and stores it in a
length instance variable.
◦ c.length;
 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.
 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.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
6.5.2 Using an Array Initializer

©1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 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
 Constant variables often make programs more
readable (instead of using literal values, e.g. 10)

©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.

©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.
©1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 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.
 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.
modify copy
or reference
affecting the
argument call example call-by original?
primitive: methodName(x) copy no
int x; (copy of the value)
primitive: methodName(a[i]) copy no
array (a) element (i: index of the (copy of the value)
element)
reference: methodName(s) reference no
String s; (copy of the ref.) (immutable)
reference: methodName(a) reference yes
array (a)

©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.
 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 we use: array[i][j]
 i identifies the element’s row and j identifies the element’s 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.
 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.
©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.
 Searching data involves determining whether a value
(referred to as the search key) is present in the data and,
if so, finding its location.
◦ Two popular search algorithms are the simple linear search and
the faster but more complex binary search.
 We’ll only study the linear search

© Copyright 1992-2015 by Pearson


Education, Inc. All Rights Reserved.
 The linear search algorithm searches each element in
an array sequentially.
◦ If the search key does not match an element in the array, the
algorithm tests each element, and when the end of the array is
reached, informs the user that the search key is not present.
◦ If the search key is in the array, the algorithm tests each
element until it finds one that matches the search key and
returns the index of that element.

© Copyright 1992-2015 by Pearson


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

You might also like