Java Reference
In-Depth Information
}
}
Arrays in Java work nicely. The type checking provides reasonable integrity, and array
bounds are always checked by the runtime system, further contributing to reliability.
The only problem with arrays is: what if the array fills up and you still have data coming in?
See Resizing an Array .
Resizing an Array
Problem
The array filled up, and you got an ArrayIndexOutOfBoundsException .
Solution
Make the array bigger. Or, use an ArrayList .
Discussion
One approach is to allocate the array at a reasonable size to begin with, but if you find your-
self with more data than will fit, reallocate a new, bigger array and copy the elements into
it. [ 27 ] Here is code that does so:
public
public class
class Array2
Array2 {
public
public final
final static
static int
int INITIAL = 10 ,
GROW_FACTOR = 2 ;
public
public static
static void
void main ( String [] argv ) {
int
int nDates = 0 ;
Date [] dates = new
new Date [ INITIAL ];
StructureDemo source = new
new StructureDemo ( 21 );
Date c ;
while
while (( c =( Date )( source . getDate ())) != null
null ) {
// if (nDates >= dates.length) {
// System.err.println("Too Many Dates! Simplify your life!!");
// System.exit(1); // wimp out
 
 
 
Search WWH ::




Custom Search