您的位置:首页 > 编程语言 > PHP开发

JHTP小结_第七章_数组及动态数组(Array and ArrayList)

2016-07-07 10:22 441 查看

Summary

Section 7.1Introduction

• Arrays (p. 244) arefixed-length data structures consisting of related data items of the same type.

Section 7.2 Arrays

• An array is a group ofvariables (called elements or components; p. 245) containing values that allhave the same type. Arrays are objects, so they’re considered
reference types.

• A program refers to anyone of an array’s elements with an array-access expression (p. 245) that includesthe name of the array followed by the index of the
particular element in squarebrackets([]; p. 245).

• The first element inevery array has index zero (p. 245) and is sometimes called the zeroth element.

• An index must be anonnegative integer. A program can use an expression as an index.

• An array object knowsits own length and stores this information in a
length
instancevariable(p. 246).

Section 7.3Declaring and Creating Arrays

• To create an arrayobject, specify the array’s element type and the number of elements as part of anarray-creation expression (p. 246) that uses keyword
new.

• When an array iscreated, each element receives a default value—zero for numeric primitive-type elements,false
for boolean elements and
null
forreferences.

• In an arraydeclaration, the type and the square brackets can be combined at the beginningof the declaration to indicate that all the identifiers in the
declaration arearray variables.

• Every element of aprimitive-type array contains a variable of the array’s declared type. Everyelement of a reference-type array is a reference to an object
of the array’sdeclared type.

Section 7.4Examples Using Arrays

• A program can create anarray and initialize its elements with an array initializer (p. 248).

• Constant variables (p.250) are declared with keyword
final, must be initializedbefore they’re used and cannot be modified
thereafter.

Section 7.5Exception Handling: Processing the Incorrect Response

• An exception indicatesa problem that occurs while a program executes. The name “exception” suggeststhat the problem occurs infrequently—if the “rule” is
that a statement normallyexecutes correctly, then the problem represents the “exception to the rule.”

• Exception handling (p.256) enables you to create fault-tolerant programs.

• When a Java programexecutes, the JVM checks array indices to ensure that they’re greater than orequal to 0 and less than the array’s length. If a program
uses an invalidindex, Java generates an exception (p. 256) to indicate that an error occurredin the program at execution time.

• To handle an exception,place any code that might throw an exception (p. 256) in a
try
statement.

• The
try
block (p.256) contains the code that might throw an exception, and the
catch
block (p.256) contains the code that handles the exception if one occurs.

• You can have many
catch
blocks tohandle different types of exceptions that might be thrown in the corresponding
try
block.

• When a
try
blockterminates, any variables declared in the
try
block go outof scope.

• A
catch
blockdeclares a type and an exception parameter. Inside the
catch
block, youcan use the parameter’s identifier to interact with a caught exception object.

• When a program isexecuted, array element indices are checked for validity—all indices must be greaterthan or equal to 0 and less than the length of the
array. If an attempt is madeto use an invalid index to access an element, an
ArrayIndexOutOfRangeException(p. 257) exception occurs.

• An exception object’s
toString
methodreturns the exception’s error message.

Section 7.6 CaseStudy: Card Shuffling and Dealing Simulation

• The
toString
method of anobject is called implicitly when the object is used where a
String
is expected(e.g., when
printf
outputs the object as a
String
using the
%s
formatspecifier or when the object is concatenated to a
String
using the
+
operator).

Section 7.7Enhanced
for
Statement


• The enhanced
for
statement (p.262) allows you to iterate through the elements of an array or a

collection without usinga counter. The syntax of an enhanced
for
statement is:

for
(parameter
:
arrayName)
statement
where
parameter
has a typeand an identifier (e.g.,
int number), and
arrayName
is the array
through which to iterate.

• The enhanced
for
statementcannot be used to modify elements in an array. If a program needs to modifyelements, use the traditional counter-controlled
for
statement.

Section 7.8Passing Arrays to Methods

• When an argument ispassed by value, a copy of the argument’s value is made and passed to the calledmethod. The called method works exclusively with the
copy.

Section 7.9Pass-By-Value vs. Pass-By-Reference

• When an argument ispassed by reference (p. 265), the called method can access the argument’s valuein the caller directly and possibly modify it.

• All arguments in Javaare passed by value. A method call can pass two types of values to a method—copiesof primitive values and copies of references to objects.
Although an object’sreference is passed by value (p. 265), a method can still interact with the referencedobject by calling its
public
methods using the copy of the object’s reference.

• To pass an objectreference to a method, simply specify in the method call the name of thevariable that refers to the object.

• When you pass an arrayor an individual array element of a reference type to a method, the called methodreceives a copy of the array or element’s reference.
When you pass anindividual element of a primitive type, the called method receives a copy ofthe element’s value.

• To pass an individualarray element to a method, use the indexed name of the array.

Section 7.11Multidimensional Arrays

• Multidimensional arrayswith two dimensions are often used to represent tables of values consisting ofinformation arranged in rows and columns.

• A two-dimensional array(p. 272) with
m
rows and
n
columns is called an
m-by-n
array. Suchan array can be initialized with an array initializer of the form
arrayType[][]
arrayName
= {{row1 initializer},
{row2 initializer},
…};

• Multidimensional arraysare maintained as arrays of separate one-dimensional arrays. As a result, thelengths of the rows in a two-dimensional array are not
required to be the same.

• A multidimensionalarray with the same number of columns in every row can be created with an array-creationexpression of the form
arrayType[][]
arrayName
=
new
arrayType[numRows][numColumns];

Section 7.13Variable-Length Argument Lists

• An argument typefollowed by an ellipsis (...;
p. 281) in a method’s parameter list indicates that the methodreceives a variable number of arguments of that particular type. The ellipsiscan occur only once in a method’s parameter list. It must be at the end of theparameter list.

• A variable-lengthargument list (p. 281) is treated as an array within the method body. Thenumber of arguments in the array can be obtained using the array’s
length
field.

Section 7.14 UsingCommand-Line Arguments

• Passing arguments to
main
(p. 283) fromthe command line is achieved by including a parameter of type
String[]
in theparameter list of
main. By convention,
main’s parameter is named
args.

• Java passescommand-line arguments that appear after the class name in the
java
command to theapplication’s
main
method as
Strings in the array
args.

Section 7.15 ClassArrays

• Class
Arrays
(p. 285)provides
static
methods that perform common array manipulations, including
sort
to sort anarray,
binarySearch
to search a sorted array,
equals
to comparearrays and
fill
to place items in an array.

• Class
System’s
arraycopy
method (p.285) enables you to copy the elements of one array into another.

Section 7.16Introduction to Collections and Class
ArrayList


• The Java API’scollection classes provide efficient methods that organize, store and retrieve datawithout requiring knowledge of how the data is being stored.

• An
ArrayList<T>(p. 288) is similar to an array but can be dynamically
resized.

• The
add
method (p.290) with one argument appends an element to the end of an
ArrayList.

• The
add
method withtwo arguments inserts a new element at a specified position in an
ArrayList.

• The
size
method (p.290) returns the number of elements currently in an
ArrayList.

• The
remove
method with areference to an object as an argument removes the first element that matchesthe argument’s value.

• The
remove
method withan integer argument removes the element at the specified index, and allelements above that index are shifted down by one.

• The
contains
method returns
true
if the element is found in the
ArrayList, and
false
otherwise.


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: