Fixed size collections (arrays)
An array is a fixed size, ordered, and indexed collection of elements of the same type.
Essentially a set of variables of the same type, where each variable has a number (index).
bucket – a particular piece of memory in an array that holds an element
element – the value stored in a bucket
index – the number associated with a bucket
An array is an object that must be created using the keyword new
When an array object is created, you must provide:
1. the type of elements that will be stored in the array
2. the number of buckets in the array
Once created, the number of buckets an array holds cannot be changed.
Example
char[] ca; // declares a reference to an array of characters
// ca initialized to nul (the char with ascii value 0)
ca = new char[6];
// creates an array object holding 6 elements (chars)
// pointer to the new array object stored in ca.
Arrays are declared with the [] operator, which has higher precedence than any other Java operator.
For most applications, you must deal with only one element at a time.
Often use loops to initialize arrays, almost always use loops to walk arrays (visit each element).
The first bucket in an array has index 0.
The syntax for referring to a particular bucket in an array is:
<variable_holding_pointer_to_the_array> [ <index_of_bucket> ]
For example, to retrieve the first character in the array above that holds 6 chars, and store this char in a variable, type:
char c = ca[0];
Walk an array with a loop
Write a method that will:
1. Receive an integer that is the size of an array as a parameter.
2. Declare a local array of chars of the size passed in.
3. Write a loop that Initializes the array, so that bucket 0 holds ‘a’, bucket 1 holds ‘b’, etc.
4. Write another loop that prints the values stored in the array.
(see ../demos/W09N02.java) – we will write this demo in class
ArrayIndexOutOfBoundsException
Attempting to reference an index that is not in the array causes ArrayIndexOutOfBoundsException to be thrown. For example, attempting to reference ca[6] in the example array above.