|
Arrays
An Introduction with Examples in Java |
|
Prof. David Bernstein
|
| Computer Science Department |
| bernstdh@jmu.edu |
An array is a contiguous block of memory that can be used to hold a fixed number of homogeneous elements.
[]
Modifier:
int[] income;
[]
Operator:
income[5] = 250000;
total = income[3];
One can declare an array and assign all of the elements to it using an "array literal" (formally, an array initializer) as follows:
One can then assign elements or access elements using the []
operator.
One can declare an array and assign default values to all of the elements to it as follows:
One can then assign elements or access elements using the []
operator.
ArrayIndexOutOfBounds "error" will be
generated)
x = payment(income[0]);
payment(int[] income)
main(String[] args)
y = payment(taxableIncome);
public int[] schedule(){...}
length contains the number of elements (and
is initialized when memory is allocated)clone() makes a (shallow) copylength Attribute
List is used to provide this kind of
functionalityList literals are written using
[ and ] (not {
and })List can be obtained
using the len() function
-1 can be used to
work with the last element of the List
: in the "index" (e.g., data[2:5])in operator can be used to
determine if a List contains a particular elementList
can be changed using the append(), insert(),
extend(), and remove() methods