Java Reference
In-Depth Information
int [ ] lhs = new int [ 100 ];
int [ ] rhs = new int [ 100 ];
...
lhs = rhs;
is that the array object that was referenced by rhs is now also referenced by
lhs . Thus changing rhs[0] also changes lhs[0] . (To make lhs an independent
copy of rhs , one could use the clone method, but often making complete cop-
ies is not really needed.)
Finally, an array can be used as a parameter to a method. The rules follow
logically from our understanding that an array name is a reference. Suppose
we have a method methodCall that accepts one array of int as its parameter.
The caller/callee views are
methodCall( actualArray ); // method call
void methodCall( int [ ] formalArray ) // method declaration
In accordance with the parameter-passing conventions for Java reference
types, formalArray references the same array object as actualArray . Thus
formalArray[i] accesses actualArray[i] . This means that if the method modi-
fies any element in the array, the modifications will be observable after the
method execution has completed. Also note that a statement such as
The contents of an
array are passed by
reference.
formalArray = new int [ 20 ];
has no effect on actualArray . Finally, since array names are simply references,
they can be returned.
2.4.2 dynamic array expansion
Suppose we want to read a sequence of numbers and store them in an array
for processing. The fundamental property of an array requires us to declare a
size so that the compiler can allocate the correct amount of memory. Also, we
must make this declaration prior to the first access of the array. If we have no
idea how many items to expect, then it is difficult to make a reasonable choice
for the array size. This section shows how to expand arrays if the initial size is
too small. This technique is called dynamic array expansion and allows us to
allocate arbitrary-sized arrays and make them larger or smaller as the program
runs.
The allocation method for arrays that we have seen thus far is
Dynamic array
expansion allows us
to allocate arbi-
trary-sized arrays
and make them
larger if needed.
int [ ] arr = new int[ 10 ];
Suppose that we decide, after the declarations, that we really need 12 int s
instead of 10. In this case, we can use the following maneuver, which is illus-
trated in Figure 2.5:
 
Search WWH ::




Custom Search