Java Reference
In-Depth Information
Before using the array elements, we must first create an object for each array
element to reference. For example,
strArray[0] = new String ("Alice");
strArray[1] = new String ("Bob");
strArray[2] = new String ("Cindy");
strArray[3] = new String ("Dan");
strArray[4] = new String ("Ed");
This code sets each element to reference a particular string.
Note that there is an alternative declaration that only works for String
objects:
strArray[0] =" Alice " ;
That is, the string literal " Alice " is equivalent to new String ( " Alice " ) .
4.7.2 Array copying
A copy of an array can be made with the static method System.arrayCopy()
as shown here:
System.arraycopy (Object src, int src - position,
Object dst, int dst - position, int length)
Here src is the array to be copied and dst is the destination array (of the
same type). The copy begins from the array element at the index value of
src - position and starts in destination at dst - position for length num-
ber of elements. If the value of the length parameter is too long, or if any
situation occurs such that either the source or destination arrays are accessed
beyond their actual array length, then an IndexOutOfBoundsException is
thrown at runtime. This optimized method works for primitive arrays as well as
object arrays. It even handles the case where the destination array overlaps the
source array.
4.7.3 Multi-dimensional arrays
In Java, multi-dimensional arrays are arrays of arrays. That is, each element is a
reference to an array object. For example, we could declare a two-dimensional
array as follows:
String[][] str = new String[3][2];
This is equivalent to
String [][] str = new String[3][];
str[0] = new String[2];
str[1] = new String[2];
str[2] = new String[2];
Search WWH ::




Custom Search