Thursday, 26 April 2018

Core Java: Array

Suppose that you want to find the average of the marks for a class of 30 students, you certainly do not want to create 30 variables: mark1, mark2, ..., mark30. Instead, You could use a single variable, called an array, with 30 elements.
An array is an ordered collection of elements of the same type, identified by a pair of square brackets [ ]. To use an array, you need to:
Declare the array with a name and a type. Use a plural name for array, e.g., marks, rows, numbers. All elements of the array belong to the same type.
Allocate the array using new operator, or through initialization, e.g., 

 
·        int[] marks;  // Declare an int array named marks
o       // marks contains a special value called null.
·        int marks[];  // Same as above, but the above syntax recommended
marks = new int[5];   // Allocate 5 elements via the "new" operator
·        // Declare and allocate a 20-element array in one statement via "new" operator
int[] factors = new int[20];
·        // Declare, allocate a 6-element array thru initialization
int[] numbers = {11, 22, 33, 44, 55, 66}; // size of array deduced from the number of items
·        When an array is constructed via the new operator, all the elements are initialized to their default value, e.g., 0 for int, 0.0 for double, false for boolean, and null for objects. [Unlike C/C++, which does NOT initialize the array contents.]
When an array is declared but not allocated, it contains a special value called null.
You can refer to an element of an array via an index (or subscript) enclosed within the square bracket [ ]. Java's array index begins with zero (0). For example, suppose that marks is an int array of 5 elements, then the 5 elements are: marks[0], marks[1], marks[2], marks[3], and marks[4].
int[] marks = new int[5];   // Declare & allocate a 5-element int array
// Assign values to the elements
marks[0] = 95;
marks[1] = 85;
marks[2] = 77;
marks[3] = 69;
marks[4] = 66;
System.out.println(marks[0]);
System.out.println(marks[3] + marks[4]);
To create an array, you need to known the length (or size) of the array in advance, and allocate accordingly. Once an array is created, its length is fixed and cannot be changed. At times, it is hard to ascertain the length of an array (e.g., how many students?). Nonetheless, you need to estimate the length and allocate an upper bound. This is probably the major drawback of using an array.

In Java, the length of array is kept in an associated variable called length and can be retrieved using "arrayName.length", e.g.,
int[] factors = new int[5];       // Declare and allocate a 5-element int array
int numFactors = factors.length;  // numFactor is 5

The index of an array is between 0 and arrayName.length - 1.
Unlike languages like C/C++, Java performs array index-bound check at the runtime. In other words, for each reference to an array element, the index is checked against the array's length. If the index is outside the range of [0, arrayName.legnth-1], the Java Runtime will signal an exception called ArrayIndexOutOfBoundException. It is important to note that checking array index-bound consumes computation power, which inevitably slows down the processing. However, the benefits gained in terms of good software engineering out-weight the slow down in speed.
 

Array and Loop
Arrays works hand-in-hand with loops. You can process all the elements of an array via a loop, for example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * Find the mean and standard deviation of numbers kept in an array
 */
public class MeanStdArray {
   public static void main(String[] args) {
      int[] marks = {74, 43, 58, 60, 90, 64, 70};
      int sum = 0;
      int sumSq = 0;
      int count = marks.length;
      double mean, stdDev;
      for (int i=0; i<count; ++i) {
         sum += marks[i];
         sumSq += marks[i]*marks[i];
      }
      mean = (double)sum/count;
      System.out.printf("Mean is %.2f%n", mean);
      stdDev = Math.sqrt((double)sumSq/count - mean*mean);
      System.out.printf("Std dev is %.2f%n", stdDev);
   }
}
  
Enhanced for-loop (or "for-each" Loop) (JDK 1.5)
JDK 1,5 introduces a new loop syntax known as enhanced for-loop (or for-each loop) to facilitate processing of arrays and collections. It takes the following syntax:
Syntax
Example
for ( type item : anArray ) {
   body ;
}
// type must be the same as the
// anArray's type

int[] numbers = {8, 2, 6, 4, 3};
int sum = 0;
for (int number : numbers) {   // for each int number in int[] numbers
   sum += number;
}
System.out.println("The sum is " + sum);
It shall be read as "for each element in the array...". The loop executes once for each element in the array, with the element's value copied into the declared variable. The for-each loop is handy to transverse all the elements of an array or a collection. It requires fewer lines of codes, eliminates the loop counter and the array index, and is easier to read. However, for array of primitive types (e.g., array of ints), it can read the elements only, and cannot modify the array's contents. This is because each element's value is copied into the loop's variable (pass-by-value), instead of working on its original copy.
In many situations, you merely want to transverse thru the array and read each of the elements. For these cases, enhanced for-loop is preferred and recommended over other loop constructs.
  
Multi-Dimensional Array
In Java, you can declare an array of arrays. For examples:
int grid[][] = new int[12][8];   // a 12×8 grid of int
grid[0][0] = 8;
grid[1][1] = 5;
System.out.println(grid.length);      // 12
System.out.println(grid[0].length);   // 8
System.out.println(grid[11].length);  // 8
In the above example, grid is an array of 12 elements. Each of the elements (grid[0] to grid[11]) is an 8-element int array. In other words, grid is a "12-element array" of "8-element int arrays". Hence, grid.length gives 12 and grid[0].length gives 8.
public class Array2DTest {
   public static void main(String[] args) {
      int[][] grid = new int[12][8];   // A 12x8 grid, in [row][col] or [y][x]
      int numRows = grid.length;       // 12
      int numCols = grid[0].length;    // 8
  
      // Fill in grid
      for (int row = 0; row < numRows; ++row) {
         for (int col = 0; col < numCols; ++col) {
            grid[row][col] = row*numCols + col + 1;
         }
      }
  
      // Print grid
      for (int row = 0; row < numRows; ++row) {
         for (int col = 0; col < numCols; ++col) {
            System.out.printf("%3d", grid[row][col]);
         }
         System.out.println();
      }
   }
}
To be precise, Java does not support multi-dimensional array directly. That is, it does not support syntax like grid[3, 2] like some languages. Furthermore, it is possible that the arrays in an array-of-arrays have different length.
Take note that the right way to view the "array of arrays" is as shown, instead of treating it as a 2D table, even if all the arrays have the same length.
For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Array2DWithDifferentLength {
   public static void main(String[] args) {
      int[][] grid = {
         {1, 2},
         {3, 4, 5},
         {6, 7, 8, 9}
      };

      // Print grid
      for (int y = 0; y < grid.length; ++y) {
         for (int x = 0; x < grid[y].length; ++x) {
            System.out.printf("%2d", grid[y][x]);
         }
         System.out.println();
      }

      int[][] grid1 = new int[3][];
      grid1[0] = new int[2];
      grid1[1] = new int[3];
      grid1[2] = new int[4];

      // Print grid - all elements init to 0
      for (int y = 0; y < grid1.length; ++y) {
         for (int x = 0; x < grid1[y].length; ++x) {
            System.out.printf("%2d", grid1[y][x]);
         }
         System.out.println();
      }
   }
}
 

No comments:

Post a Comment

Please write your view and suggestion....