Arrays
Arrays
Overview
Arrays
are the only collection support defined within the Java programming language.
They are objects that store a set of elements in an order accessible by index
, or position
They are subclass of Object
and implement both Serializable
and Cloneable
interfaces
Cloneable
When creating a Java application, the main() method has a single argument that is a String array: public static void main(String args[].
The compiler doesn't care what argument name you use, only that it is an array of String objects
Because an array's size does not change as we walk through the loop, there is no need to look up the length for each test case, as in
public class Arrays { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println("Arg: " + i + ": " + args[i]); } } }In fact, to go through the loop counting down instead of up as a check for zero test case is nominally faster in most instances:
public class Arrays { public static void main(String[] args) { for (int i = args.length; i >= 0; i--) { System.out.println("Arg: " + i + ": " + args[i]); } } }To demonstrate the speed difference on your platform, try out the program below to time how long it takes to loop
"max int"
times:package cloud.yebei.java.collections.arrays; public class TimeArray { public static void main(String[] args) { int something = 2; long startTime = System.currentTimeMillis(); for (int i = 0, n = Integer.MAX_VALUE; i < n; i++) { something = -something; } long midTime = System.currentTimeMillis(); for (int i = Integer.MAX_VALUE - 1; i >= 0; i--) { something = -something; } long endTime = System.currentTimeMillis(); System.out.println("Increasing Delta: " + (midTime - startTime)); System.out.println("Decreasing Delta: " + (endTime - midTime)); } }This test program is really timing the for−loop and not the array access because there is no array access.
If you ever try to access before the beginning or after the end of an array, an ArrayIndexOutOfBoundsException
will be thrown. As a subclass of IndexOutOfBoundsException
, the ArrayIndexOutOfBoundsException
is a runtime exception
Thankfully, this means that you do not have to place array accesses within try−catch blocks.
In addition, since looking beyond the bounds of an array is a runtime exception, your program will compile just fine. The program will only throw the exception when the access is attempted.
The class hierarchy of ArrayIndexOutOfBoundsException
The following code demonstrates an improper way to read through the command−line array elements: