Java Reference
In-Depth Information
figure 2.7
Code to read an
unlimited number of
String
s and output
them (part 2)
29
// Resize a String[ ] array; return new array
30
public static String [ ] resize( String [ ] array,
31
int newSize )
32
{
33
String [ ] original = array;
34
int numToCopy = Math.min( original.length, newSize );
35
36
array = new String[ newSize ];
37
for( int i = 0; i < numToCopy; i++ )
38
array[ i ] = original[ i ];
39
return array;
40
}
41
42
public static void main( String [ ] args )
43
{
44
String [ ] array = getStrings( );
45
for( int i = 0; i < array.length; i++ )
46
System.out.println( array[ i ] );
47
}
48
}
The
add
method increases the size by one, and adds a new item into the
array at the appropriate position. This is a trivial operation if capacity has not
been reached. If it has, the capacity is automatically expanded, using the strat-
egy described in Section 2.4.2. The
ArrayList
is initialized with a size of
0
.
Because indexing via
[]
is reserved only for primitive arrays, much as was
the case for
String
s, we have to use a method to access the
ArrayList
items. The
get
method returns the object at a specified index, and the
set
method can be
used to change the value of a reference at a specified index;
get
thus behaves
like the
charAt
method. We will be describing the implementation details of
ArrayList
at several points in the text, and eventually write our own version.
The code in Figure 2.8 shows how
add
is used in
getStrings
; it is clearly
much simpler than the
getStrings
function in Section 2.4.2. As shown at line
19, the
ArrayList
specifies the type of objects that it stores. Only the speci-
fied type can be added to the
ArrayList
; other types will cause a compile-
time error. It is important to mention, however, that only objects (which are
accessed by reference variables) can be added into an
ArrayList
. The eight
primitive types cannot. However, there is an easy workaround for that,
which we will discuss in Section 4.6.2.
The specification of the type is a feature added in Java 5 known as
generics
. Prior to Java 5, the
ArrayList
did not specify the type of objects,
and any type could be added to the
ArrayList
. For backward compatibility,
The
add
method
increases the size
by 1 and adds a
new item to the
array at the appro-
priate position,
expanding capacity
if needed.
Search WWH ::
Custom Search