Arrays

Definition

An array is an indexed collection of data elements of the same type.
  1. Indexed means that the array elements are numbered (starting at 0).
  2. The restriction of the same type is an important one, because arrays are stored in consecutive memory cells. Every cell must be the same type (and therefore, the same size).

Creating Arrays

Two steps:
  1. Declare an array variable (a reference to the array)
  2. Create the array

Formats for declaring an array variable:

  type[] arrayName;    // preferred
  type arrayName[];    // alternate form

Format for creating the array (with the operator new)

  arrayName = new type[size];   // type should match the type of the arrayName variable
Examples:
  int[] list;		   // declare an array variable, "list"
  list = new int[30];	   // creates an array of 30 integers

  char[] name;		   // declare array variable, "name"
  name = new char[20];     // creates an array of 20 chars

  double[] nums;	   // declare array variable, "nums"
  nums = new double[x];    // creates an array of x doubles

Combined format:

  type[] arrayName = new type[size];
Examples:
  int[] list = new int[30];
  char[] name = new char[20];
  double[] nums = new double[x];
The array's size is stored in arrayName.length. For example, the size of the "list" array above is:
  list.length

Initializing and Using Arrays

When array of a built-in type is created, elements are automatically initialized Once an array is created, the notation arrayName[index] refers to a specific array slot -- the one at the given index position. Examples:
  int x;
  int[] list = new int[5];         // create array 
  double[] nums = new double[10];  // create array

  list[3] = 6;                     // assign value 6 to array item with index 3
  System.out.print(nums[2]);       // output array item with index 2 
  list[x] = list[x+1];

  // set values in list array to {1, 3, 5, 7, 9} 
  for (int i = 0; i < list.length; i++)
	list[i] = i * 2 + 1;
Note that this last example, the for-loop, illustrates a good way to set all values in an array. Arrays and for-loops go great together!

A Shortcut

The following format can be used to declare, create, and initialize an array in one line. (Note that this also bypasses the new operation, which is implicit):
   type[] arrayName = { initializer list };
The initializer list is a comma-separated list of array values. From this, the compiler can figure out the number of elements when creating the array. Examples:
  int[] list = {2, 4, 6, 8, 10, 12, 14, 16};   // has size 8
  double[] grades = {96.5, 88.4, 90.3, 70.1};  // has size 4
  char[] vowels = {'a', 'e', 'i', 'o', 'u'};   // size 5

Passing arrays to methods

Copying Arrays

If we have these two arrays, how do we copy the contents of list2 to list1?
  int[] list1 = new int[5]; 
  int[] list2 = {3, 5, 7, 9, 11}; 

With variables, we use the assignment statement, so this would be the natural tendency -- but it is wrong!

  list1 = list2;  // this does NOT copy the array contents 

We must copy between arrays element by element. A for loop makes this easy, however:

  for (int i = 0; i < list2.length; i++) 
    list1[i] = list2[i]; 
There is also a method called arraycopy in the java.lang.System class. It's format is:
  arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);
src_pos and tar_pos indicate the starting positions to use in the copy process. length is the number of elements to be copied. Sample call:
  // this call is equivalent to the for-loop example above
  System.arraycopy(list2, 0, list1, 0, list2.length);

Multi-dimensional Arrays

Use separate set of index brackets [] for each dimension. Examples:
  int[][] table = new int[5][3];    // a 5 x 3 table of integers
  short[][] matrix = { {3, 4, 5},
		       {1, 2, 3},
		       {0, 5, 9},
		       {8, 1, -2} };  // a 4 x 3 matrix of short integers
For a 2 dimensional array, we usually think of the first size as rows, and the second as columns, but it really does not matter, as long as you are consistent! We could think of the first array above as a table with 5 rows and 3 columns, for example.

When using a multi-dimensional array, make sure that the indices are always used in the same order:

  table[3][1] = 5;	// assigns a 5 to "row 3, column 1", in the above interpretation

Arrays of Objects

Creating an array of objects is a little trickier than an array of a primitive type.
  1. Create an array using similar syntax to primitive types, but use the class name instead of the primitive type name:
     
      Student[] list = new Student[10];
    
    This only creates an array of reference variables -- references for type Student
     
  2. Create the individual objects with new, and attach to the reference variables (the array positions). This can be done separately:
      list[0] = new Student();
      list[1] = new Student();
    
    but it's easier with a loop (as long as you are using the same constructor for each object):
      for (int i = 0; i < list.length; i++)
        list[i] = new Student();
    
    Each list[i] is the reference to an object now.

Code Examples from Deitel, Ch. 7