Understanding the Use of Arrays
with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
What do you think of the following fragment?
total = 0.0; total = total + income1; total = total + income2; total = total + income3; total = total + income4; total = total + income5; total = total + income6; total = total + income7; mean = total / 7.0;
Arrays offer the same kinds of benefits of subscripts in mathematical notation -- this fragment is more compact, more readable, and more flexible.
total = 0.0; for (int i=0; i<n; i++) { total = total + income[i]; } mean = total / income.length;
[]
Modifier:
int[] income;
[]
Length Specifier:
income = new int[20];
[]
Operator:
income[5] = 250000;
x = payment(income[0]);
payment(int[] income)
main(String[] args)
y = meanPayment(taxableIncome);
public int[] schedule(){...}
length
contains the number of elements (and
is initialized when memory is allocated)clone()
makes a (shallow) copylength
Attributeint i; int[] strikeouts; strikeouts = new int[9]; for (i=0; i<strikeouts.length; i++) { strikeouts[i] = 0; }
length
Attribute (cont.)int i; int[] strikeouts; strikeouts = new int[9]; . . . // This will not work because the length attribute // is declared to be final (which means it cannot be // changed after it is initialized) // strikeouts.length = 5;
clone()
Methodint[] copy, original; original = new int[3]; original[0] = 2001; original[1] = 1995; original[2] = 2001; copy = original.clone();
length
NullPointerException
when using method/attribute
IndexOutOfBoundsException
when accessing
an elementArrays
Utility Class
The Arrays
class (in the java.util
package)
class contains several static methods that are very convenient when
working with arrays.
import java.util.Arrays; int target; int[] a; a = new int[100]; Arrays.fill(a, 0); // Fill a with zeroes Arrays.fill(a, 1, 10, 99) // Fill a[10] thru a[99] with ones ... Arrays.sort(a); // Sort a in ascending order // Searches for 5 in a and returns 5 if found // The array must be sorted // target = Arrays.binarySearch(a,5);