Declaring an array
- Example:
int[] a;
- Is a reference, like an object
Array allocation
- Allocating memory for an array
- Example:
a = new int[100]; (fixed size)
- all elements are set to zero (numeric), null (object types)
or false (boolean)
- Anonymous array -- Example:
int[] a = new int[]
{1,2}; -> array of length 2
- String[] words =
new String[]{"bla", "blo", "bli"};
Accessing elements
with Subscripts
-- Example: a[i] Subscript ranges always start at
zero
Java always checks Subscript legality, between 0 and size. If
not, Java throws ArrayIndexOutOfBoundsException
Array length
-- Example: a.length
- typical statement for looping over an array
for (int
i =
0;i < a.length;i++){
a[i]=10;
}
|
Two-dimensional arrays
Vectors
For dynamically extendable
arrays: use vectors of the java.util package.
vector<int> v = new vector<int>();
v.add(2);
for(int i = 0;i < v.size(); i++){
System.out.println("Element " + i + "=" +
v.get(i));
}
|