Sie sind auf Seite 1von 13

GROUP 1

Array
Most real-world programs handle vast amounts of data. Fortunately, the data usually can be
organized and processed systematically. Arrays or similar structures are almost always used for
this. When data is organized into arrays and processed in loops, a relatively small program can
handle a vast amount of data. This chapter discusses arrays and shows examples of how they
work.

Picture of an Array

An array is an object that is used to store a list of values. It is made out of a contiguous block of
memory that is divided into a number of cells. Each cell holds a value, and all the values are of
the same type. Sometimes the cells of an array are called slots. In the example array pictured at
right, each cell holds an int.
The name of this array is data. The cells are indexed 0 through 9. Each cell can be accessed by
using its index. For example, data[0] is the cell which is indexed by zero (which contains the
value 23). data[5] is the cell which is indexed by 5 (which contains the value 14).
Facts:

The cells are numbered sequentially starting at zero.

If there are N cells in an array, the indexes will be 0 through N-1.

Sometimes the index is called a subscript. The expression data[5] is usually pronounced "datasub-five" as if it were an expression from mathematics: data5.
The value stored in a cell of an array is sometimes called an element of the array. An array has a
fixed number of cells. The values in the cells (the elements) can be changed.
Q: What value is in data[7] ?
A: 103

Using Arrays
data[3] = 99 ;

Before

After

Every cell of an array holds a value of the same type. So, for example, you can have an array of
ints, an array of doubles, and so on.

You can have an array of object references. This is discussed in a later chapter.
The "before" array in the picture holds data of type int. A cell of this array can be used
anywhere a variable of type int can be used. For example,
data[3] = 99 ;

works just like an assignment to an int variable. After it has been executed, the array looks like
the "after" array in the picture.
The value in cell 3 of the array has been changed.
Q: What do you suppose is the value of the arithmetic expression:
data[2] + data[6]

A: 23
data[2]

contains a 14 and data[6] contains a 9, the sum is 23.

Arithmetic Expressions

An expression such as data[3] is called a subscripted variable. A subscripted variable can be


used anywhere an ordinary variable of the same type can be used. Since data[3] contains an
int it can be used anywhere an int variable may be used.

An arithmetic expression can contain a mix of literals, variables, and subscripted variables. For
example, if x contains a 10, then
(x + data[2]) / 4

evaluates to (10+14) / 4 == 6. Here are some other legal statements:


data[0] = (x + data[2]) / 4 ;
data[2] = data[2] + 1;
// increment the data in cell 3
x = data[3]++ ;
data[4] = data[1] / data[6];

Q: Assume that the array holds values as in the picture. What will be the result of executing the
statement:
data[0] = data[6] + 8;

A: The value 17 is put into cell 0 of data.


Arrays are Objects

Array declarations look like this:


type[] arrayName;

This tells the compiler that arrayName contains a reference to an array containing type. However,
the actual array object is not constructed by this declaration. The declaration merely declares a
reference variable arrayName which, sometime in the future, is expected to refer to an array
object.
Often an array is declared and constructed in one statement, like this:
type[] arrayName = new type[ length ];

This statement does two things: (1) It tells the compiler that arrayName will refer to an array
containing cells of type. (2) It constructs an array object containing length number of cells.
An array is an object, and like any other object in Java, it is constructed out of main storage as
the program is running. The array constructor uses different syntax than other object
constructors:
new type[ length ]

This names the type of data in each cell and the number of cells.
Once an array has been constructed, the number of cells it has does not change. Here is an
example:

int[] data = new int[10];

This statement creates an array of 10 ints, puts a zero into each cell, and puts a reference to that
object in data.
int[] data = new int[10];
Q

Q: 1.What is the length of the array data?


2. What are the indexes of data?
A: int[] data = new int[10];
1.

10

2. 0, 1, 2, ..., 8, 9

Bounds Checking
int[] data = new int[10];
data[ -1 ]
data[ 10 ]
data[ 1.5 ]
data[ 0 ]
data[ 9 ]
data[ j ]

always illegal
illegal
(given the above declaration)
always illegal
always OK
OK
(given the above declaration)
can't tell
(depends on the value of j)

Recall that:
The length of an array is how many cells it has. An array of length N has cells
indexed 0..(N-1)
Indexes must be an integer type. It is OK to have spaces around the index of a subscripted
variable, for example data[1] and data[ 1 ] are exactly the same as far as the compiler is
concerned.
It is not legal to refer to a cell that does not exist.
Say that an array were declared:
int[] data = new int[10];

The table shows some subscripted variables of this array.


If your program contains an expression that is always illegal, it will not compile. But often
the size of an array is not known to the compiler. The size of an array often is determined by
data at run time. Since the array is constructed as the program is running, the compiler does
not know its length and can't detect some errors.
As a Java program is running, each time an array index is used it is checked to be sure
that it is OK. This is called bounds checking, and is extremely important for catching
errors. If an executing program refers to a cell that does not exist, an
ArrayIndexOutOfBoundsException is thrown, and (usually) the program is terminated.
(See a future chapter for more on exceptions.)
Q: Here is a declaration of another array:
double[] scores = new double[25];

Which of the following are legal?


scores[ 0 ]
scores[1]
scores[ 10]
scores[ 25 ]
scores[ 1.2]
scores [2]
A: int[] scores = new double[25];

scores[ 0 ]

OK

scores[ 1 ]

OK

scores[ -1 ]

scores[ 10]

scores[ 25 ]

illegal

scores[ 24 ]

OK

scores[ 1.2]

illegal

scores [2]

OK

scores [ 4 ]

OK

illegal
OK

scores[ -1 ]
scores[ 24 ]
scores [ 4 ]

Array Initialization

Lacking any other information, the cells of an array are initialized to the default value for their
type. Each cell of a numeric array is initialized to zero.
Each cell of an array of object references is initialized to null. (Arrays of object references are
discussed in an upcoming chapter.)
Of course, the program can assign values to cells after the array has been constructed. In the
following, the array object is constructed and each cell is initialized to 0. Then some assignment
statements explicitly change some cells:

class ArrayEg1
{
public static void main ( String[] args )
{
int[] stuff = new int[5];
stuff[0] = 23;
stuff[1] = 38;
stuff[2] = 7*2;
System.out.println("stuff[0]
System.out.println("stuff[1]
System.out.println("stuff[2]
System.out.println("stuff[3]
System.out.println("stuff[4]

}}

Q: What does the program write?


stuff[0] has
stuff[1] has
stuff[2] has
stuff[3] has
stuff[4] has
A:

stuff[0]
stuff[1]
stuff[2]
stuff[3]
stuff[4]

has
has
has
has
has

23
38
14
0
0

has
has
has
has
has

"
"
"
"
"

+
+
+
+
+

stuff[0]
stuff[1]
stuff[2]
stuff[3]
stuff[4]

);
);
);
);
);

Using an Expression as an Index


Using an expression for an array index is a very powerful tool. You often solve a problem by
organizing the data into arrays, and then processing that data in a systematic way using variables
as indexes. See the below program.
You can, of course, copy this program to your editor, save it and run it. Arrays can get confusing.
Playing around with a simple program now will pay off later.

class ArrayEg2
{
public static void main ( String[] args )
{
double[] val = new double[4]; // an array of double
// cells initialized to 0.0
val[0] = 0.12;
val[1] = 1.43;
val[2] = 2.98;
int j = 3;
System.out.println( "cell 3: " + val[ j
] );
System.out.println( "cell 2: " + val[ j-1 ] );
j = j-2;
System.out.println( "cell 1: " + val[ j
}}

Q: What does the above program output?


cell 3:
cell 2:
cell 1:
A:
cell 3: 0.0
cell 2: 2.98
cell 1: 1.43

More Complicated Example

Here is a more complicated example:

] );

class ArrayEg3
{
public static void main ( String[] args )
{
double[] val = new double[4];
val[0] = 1.5;
val[1] = 10.0;
val[2] = 15.5;
int j = 3;
val[j] = val[j-1] + val[j-2];

// same as val[3] = val[2] + val[1]

System.out.println( "val[" + j + "] == " + val[j] );


}}

Q: What does the above program print out?


val [ ?] == ?
A:
val[3] == 25.5

Initializer Lists
You can declare, construct, and initialize the array all in one statement:
int[] data = {23, 38, 14, -3, 0, 14, 9, 103, 0, -56 };

This declares an array of int which is named data. Then it constructs an int array of 10 cells
(indexed 0..9). Finally it puts the designated values into the cells. The first value in the initializer
list corresponds to index 0, the second value corresponds to index 1, and so on. (So in this
example, data[0] gets the 23.)
You do not have to say how many cells the array has. The compiler will count the values in the
initializer list and make that many cells. Once an array has been constructed, the number of cells
does not change. Initializer lists are usually used only for small arrays.

Q: Write a declaration for an array of double named dvals that is initialized to


contain 0.0, 0.5, 1.5, 2.0, and 2.5.

A: double[] dvals = { 0.0, 0.5, 1.5, 2.0, 2.5 };

Several Arrays per Program


A program can use any number of arrays. Often values are copied back and forth between the
various arrays. Here is an example program that uses two arrays:

class ArrayEg4
{
public static void main ( String[] args )
{
int[] valA = { 12, 23, 45, 56 };
int[] valB = new int[4];

Q:

}}

Fill in the blanks so that the values in valA are copied into the corresponding cells of
valB.
A:class ArrayEg4
{
public static void main ( String[] args )
{
int[] valA = { 12, 23, 45, 56 };
int[] valB = new int[4];
valB[
valB[
valB[
valB[
}}

0
1
2
3

]
]
]
]

=
=
=
=

valA[
valA[
valA[
valA[

0
1
2
3

]
]
]
]

;
;
;
;

Copying Values from Cell to Cell

In this example, the int in cell 0 of valA is copied to cell 0 of valB, and so on.
valB[ 0 ]

= valA[ 0 ] ;

This is just like an assignment statement


spot = source;

where both variables are of primitive type int. After the four assignment statements of the
answer have executed, each array contains the same values in the same order:

Super Bug Alert: The following statement does not do the same thing:

valB = valA ;

Remember that arrays are objects. The statement above will merely copy the object reference in
valA into the object reference variable valB, resulting in two ways to access the single array
object, as seen in the second picture.
The object that valB previously referenced is now lost (it has become garbage.)
valA

and valB are now aliases for the same object.

Q: Say that the statement valB = valA had been executed, resulting in the above picture. What
would the following print out?
valA[2] = 999;
System.out.println( valA[2] + "
" + valB[2] );
A: Since valA and valB both refer to the same object, valA[2]

and valB[2] are two ways to

refer to the same cell. The statements print out:


999

999

Here is a list of facts about arrays. You may wish to refer back to a page that discusses a
particular fact in greater detail.
1. An array is an object that has room for several values, all of the same type.
2. Each value is stored in a cell of the array. The values stored in an array are sometimes
called the elements of the array.
3. If there are N cells in the array, the cells are indexed from 0 up to (N-1).
4. The index must be an integer value (byte, short, or int).
5. An array declaration looks like:
6.

int[] intArray;

This declaration declares the array reference intArray. It does not create the actual
object.
7. An array can be declared and constructed in a combined statement:
8.

int[] intArray = new int[17];

This declaration declares the array reference intArray, and constructs an array object
containing 17 cells that can hold int.
9. When an array object is constructed using the new operator, the cells are initialized to the
default value of the type of the cell. Numeric types are initialized to zero.
10. Once an array object has been constructed, the number of cells it has can not be changed.
(However, a completely new array object, with a different number of cells, can be
constructed to replace the first array object.)
11. A subscripted variable such as intArray[12] can be used anywhere an ordinary variable
of the same type can be used.
12. The index used with an array can be stored in a variable, for example
13.
14.

int j = 5 ;
intArray[ j ] = 24;

// same as: intArray[ 5 ] = 24

15. The index used with an array can be computed in an expression, for example
16.
17.

int j = 5 ;
intArray[ j*2 + 3 ] = 24;

// same as: intArray[ 13 ] = 24

18. The index used with an array must be within the range 0..(N-1) where N is is number of
cells of the array.
19. If an index that is out of bounds is used with an array, an exception is thrown and the
program stops running (unless it catches the exception.)
20. An array can be declared, constructed, and initialized using an initializer list. This can
only be done when the array is first declared.
Arrays can be confusing at first. But they are very important. If you are somewhat uncertain
about arrays, take a break. Then, sometime later, come back to this chapter and work through it
again.

Das könnte Ihnen auch gefallen