Sunday, 18 December 2011

How to initialize array elements in loop

Initializing Elements in a Loop


Array objects have a single public variable, length that gives you the number of
elements in the array. The last index value, then, is always one less than the length.
For example, if the length of an array is 4, the index values are from 0 through 3.
Often, you'll see array elements initialized in a loop as follows:


Dog[] myDogs = new Dog[6]; // creates an array of 6
// Dog references
for(int x = 0; x < myDogs.length; x++) {
myDogs[x] = new Dog(); // assign a new Dog to the
// index position x
}
The length variable tells us how many elements the array holds, but it does not
tell us whether those elements have been initialized.

Two dimensional array


2-dimensional arrays are usually represented in a row-column approach on paper, and the terms "rows" and "columns" are used in computing.

There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Java doesn't do this. Instead Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. [C++ supports both styles.]



A two-dimensional array (an array of arrays) can be initialized as follows:
int[][] scores = new int[3][];
// Declare and create an array holding three references
// to int arrays
scores[0] = new int[4];
// the first element in the scores array is an int array
// of four int elements
scores[1] = new int[6];
// the second element in the scores array is an int array
// of six int elements
scores[2] = new int[1];
// the third element in the scores array is an int array
// of one int element

Java Anonymous array

Anonymous array

They are used to construct and initializing the array and then assigning the array to previously declare array reference variable.


Following is the example of creating anonymous array



int[] testScores;
testScores = new int[] {4,7,2};


The preceding code creates a new int array with three elements, initializes the
three elements with the values 4, 7, and 2, and then assigns the new array to
the previously declared int array reference variable testScores. We call this
anonymous array creation because with this syntax you don't even need to assign
the new array to anything