Java Reference
In-Depth Information
(See figure above.) Or, even better, use an ArrayList<BankAccount> .
Why is this beneficial? Think ahead. Maybe your program will change and you
will need to store the owner of the bank account as well. It is a simple matter to
update the BankAccount class. It may well be quite complicated to add a new
array and make sure that all methods that accessed the original two arrays now also
correctly access the third one.
A DVANCED T OPIC 7.4: Partially Filled Arrays
Suppose you write a program that reads a sequence of numbers into an array. How
many numbers will the user enter? You can't very well ask the user to count the
items before entering themÈŒthat is just the kind of work that the user expects the
computer to do. Unfortunately, you now run into a problem. You need to set the
size of the array before you know how many elements you need. Once the array
size is set, it cannot be changed.
To solve this problem, make an array that is guaranteed to be larger than the
largest possible number of entries, and partially fill it. For example, you can decide
that the user will never enter more than 100 data values. Then allocate an array of
size 100:
final int DATA_LENGTH = 100;
double[] data = new double[DATA_LENGTH];
Then keep a companion variable that tells how many elements in the array are
actually used. It is an excellent idea always to name this companion variable by
adding the suffix Size to the name of the array.
int dataSize = 0;
316
Search WWH ::




Custom Search