Java Reference
In-Depth Information
figure 2.6
Code to read an
unlimited number of
String s and output
them (part 1)
1 import java.util.Scanner;
2
3 public class ReadStrings
4 {
5 // Read an unlimited number of String; return a String [ ]
6 // The minimal I/O details used here are not important for
7 // this example and are discussed in Section 2.6.
8 public static String [ ] getStrings( )
9 {
10 Scanner in = new Scanner( System.in );
11 String [ ] array = new String[ 5 ];
12 int itemsRead = 0;
13
14 System.out.println( "Enter strings, one per line; " );
15 System.out.println( "Terminate with empty line: " );
16
17 while( in.hasNextLine( ) )
18 {
19 String oneLine = in.nextLine( );
20 if( oneLine.equals( "" ) )
21 break;
22 if( itemsRead == array.length )
23 array = resize( array, array.length * 2 );
24 array[ itemsRead++ ] = oneLine;
25 }
26
27 return resize( array, itemsRead );
28 }
At the start of getStrings , itemsRead is set to 0 and we start with an initial
five-element array. We repeatedly read new items at line 23. If the array is full,
as indicated by a successful test at line 26, then the array is expanded by call-
ing resize . Lines 42 to 48 perform the array expansion using the exact strat-
egy outlined previously. At line 28, the actual input item is assigned to the
array and the number of items read is incremented. If an error occurs on input,
we simply stop processing. Finally, at line 36 we shrink the array to match the
number of items read prior to returning.
2.4.3 ArrayList
The technique used in Section 2.4.2 is so common that the Java library con-
tains an ArrayList type with built-in functionality to mimic it. The basic idea
is that an ArrayList maintains not only a size, but also a capacity; the capacity
is the amount of memory that it has reserved. The capacity of the ArrayList is
really an internal detail, not something that you need worry about.
The ArrayList is
used for expanding
arrays.
 
Search WWH ::




Custom Search