Monday 16 January 2012

Arrays in Java

Java Array Declaration

Java Array Instantiation
Shorthand method
Java has a shorthand to create an array object and supply initial values at the same time. Here's an example of the syntax at work:

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
Notice that you do not call new when you use this syntax. 

Memory Allocation and initialization
char[] s = new char[10];
for( int i=0; i<26; i++){
    s[i] = (char) ('A' + i);
  }

Array of references can be made similarly:
Point[] p = new Point[26];


No need to pass length of array to function unlike in cpp
To find the number of elements of an array, use array.length. For example,
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);


Iterating over array
Java provides 2 ways of iterating over arrays.
Traditional or old style iteration
for (int i = 0; i < a.length; i++)
    System.out.println(a[i]);


New style

JDK 5.0 introduces a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values.

for (variable : collection)
    statement

sets the given variable to each element of the collection and then executes the statement (which, of course, may be a block). The collection expression must be an array or an object of a class that implements the Iterable interface, such as ArrayList For example,



for (int element : a)
    System.out.println(element);

So here we are taking element from array a and dumping it on output.

Note: println prints each element of the array a on a separate line.

You should read this loop as "for each element in a". The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already contains methods or variables with the same names (such as System.in).

"for each" vs for
The loop variable of the "for each" loop traverses the elements of the array, not the index values.
The "for each" loop is a pleasant improvement over the traditional loop if you need to process all elements in a collection. However, there are still plenty of opportunities to use the traditional for loop. For example, you may not want to traverse the entire collection, or you may need the index value inside the loop.
Jakarta ArrayUtils class: http://jakarta.apache.org/commons/lang/api/index.html

No comments:

Post a Comment