Java Reference
In-Depth Information
S ELF C HECK
11. How do you declare and initialize a 4-by-4 array of integers?
12. How do you count the number of spaces in the tic-tac-toe board?
H OW T O 7.1: Working with Array Lists and Arrays
Step 1 Pick the appropriate data structure.
As a rule of thumb, your first choice should be an array list. Use an array
if you collect numbers (or other primitive type values) and efficiency is
an issue, or if you need a two-dimensional array.
Step 2 Construct the array list or array and save a reference in a variable.
For both array lists and arrays, you need to specify the element type. For
an array, you also need to specify the length.
ArrayList<BankAccount> accounts = new
ArrayList<BankAccount>();
double[] balances = new double[n];
Step 3 Add elements.
For an array list, simply call the add method. Each call adds an element
at the end.
accounts.add(new BankAccount(1008));
accounts.add(new BankAccount(1729));
For an array, you use index values to access the elements.
balance[0] = 29.95;
balance[1] = 1000;
Step 4 Process elements.
The most common processing pattern involves visiting all elements in
the collection. Use the Ȓfor eachȓ loop for this purpose:
for (BankAccount a : accounts)
Search WWH ::




Custom Search