Here is how you would allocate an array of primitives:
ArrayIndexOutOfBoundsException is the exception that will be thrown if you use an index outside the range 0..N-1 where N is the allocated size of the array.
The key thing to understand is initialising is a two step process:
Newbies tend to ignore one of those two steps, both of which you must do explicitly.
Here is how you would allocate an array of objects using Java’s short hand syntax:
String[] fruits = { "banana" , "pear" , "orange" , null, favouriteFruit() };
If your array type is declared abstract, you can still do stage 1. However, for stage 2, you need to populate with actual Objects derived from that abstract type.
You can initialise an array to a list of values this way:
String[] fruits; ... fruits = new String[] { "banana" , "pear" , "orange" , null, favouriteFruit() };
You can also do it with Arrays.fill
import java.util.Arrays; ... int[] numbers = new int[ 50 ]; Arrays.fill( numbers, 149 );
Methods can return arrays. Usually the callee allocates them. However, the caller could allocate them and pass them as parameters.
Here are some ways from simple to complex that you can return an array of Strings from a method.
An array is a fixed length block of primitives or references. If you need something that will grow automatically, see ArrayList or Vector or some other Collection. Java never stores blocks of repeating structures or objects. It always creates contiguous blocks of references to separately stored objects. Novices make two common errors: failing to allocate space for the array and failing to allocate objects for each cell. Java automatically initialises arrays of primitives to 0 and arrays of references to null. However, it won’t create any objects for you automatically. Here is how you would allocate an array of primitives:
// note how you never specify the array's size in its type declaration. int[] v; // allocate space for the array v = new int [100]; for ( int i = 0; i < v.length; i++ ) { v[i] = i*2 + 999; }Here is how you would allocate
Cell[] v = new Cell [100]; for ( int i=0; i<v.length; i++ ) { v[i] = new Cell( i, 999 ); }Here is an error only rank newbies make. They declare an array:
long[] a;then allocate the array, but improperly redeclare the array:
long[] a = new long[100];This does not work because you have declared a local stack variable, unrelated to the first one. Make sure you do it like this:
long[] a; // then later initialise it with: a = new long [100];Here is how to allocate an array initialised to a set of constants:
int[] array = { 11, 12 , 13, 21, 22, 21, 31, 32, 33 };The same technique works with arrays of objects:
BigDate[] dates = { new BigDate( 1999, 1, 1 ), new BigDate( 1999, 12, 31 ) };You might think you could similarly assign an array constant to an array like this:
array = { 11, 12, 13, 21, 22, 21, 31, 32, 33 };However, the syntax needed (introduced with Java version 1.1 ) is more verbose:
array = new int[] { 11, 12 , 13, 21, 22 , 21, 31, 32 , 33 };You can put in an extra comma at the end, without ill effect. This makes maintaining vertical lists easier:
array = new int[] { 11, 12, 13, 21, };Here is how you can create anonymous initialised arrays, use once and discard.
Under the hood, to find an element, you first index by row into a contiguous block of pointers. That points you to the start of one of another contiguous block of pointers. You index into that block by column, which points you to associated object. If you had a 3 × 5 matrix of objects you would have 1+3+(3*5)=19 separate allocation regions for the matrix and its objects.
Here is the generalized way you would use declare and initialize a 3 × 4 rectangular matrix.
Initialising a matrix:// This is the usual shorthand way to initialise a matrix. int[][] mat = new int[3][5]; for ( int i=0; i<3; i++ ) { for ( int j=0; j<5; j++ ) { mat[i][j] = i*j+100; } }And here is a more realistic way, avoiding hard coded constants: If you fail to initialise the array, Java automatically initialises it for you to zeroes. If you have a matrix of objects and you fail to initialise, Java initialises it to nulls for you. It does not allocate empty objects at each grid point for you. You have to allocate the objects yourself like this:
Cell[][] mat = new Cell[3][5]; for ( int i=0; i<3; i++ ) { for ( int j=0; j<5; j++ ) { mat[i][j] = new Cell( i, j, 100 ); } }Allocating and initialising a triangular matrix: Initialising a matrix to constants:
int[][] mat = { { 11 , 12, 13} , { 21, 22 , 21} , { 31 , 32, 33}};You might think you could similarly assign a matrix constant to an array like this:
mat = { { 11, 12, 13} , { 21, 22, 21} , { 31, 32, 33}};However, the syntax needed (introduced with Java version 1.1) is more verbose: In all these examples, you can use mat.length and mat[i].length to avoid repeating the constants that define the matrix’s dimensions.
For serious matrix work you need a matrix package such as MTJ.
Arrays are like virgins. They are very careful about what they allow in themselves. When you construct an array you declare what sorts of Object you are going to allow into the array. You cannot violate that sacred trust:
For example:
Dog[] mutts = new Dalmatian[20]; mutts[2] = new PitBull(); /* Prang!! */
This will get you an ArrayStoreException since the array, as constructed, only allows Dalmatians (or their subclasses) in it, even though the declaration says it will allow any Dog in.
however, this:
Dog[] mutts = new Dog [20]; mutts[2] = new PitBull(); /* is perfectly ok */
Whenever you store an Object into an array, at run time, the JVM (Java Virtual Machine) checks to make sure the object is of a compatible type. There are a few cases where this check is not necessary, e.g. if Dog had no subclasses.
A common error is to have an Object[] returned from Vector in which all the elements actually are Strings. You can cast the elements individually from Object to String, but you can’t cast the entire array object, Object[] to String[], even if all the individual elements currently happen to be Strings. You could only cast Object[] to String[] if the array Object actually were created as a String[]. To get around this problem, to ensure Vector gives you an array of Strings instead of an array of Objects, use code like this to extract arrays from Vectors:
String[] strArray = ( String[])v.toArray( new String [v.size()] );
System.arraycopy will copy element by element casting each as necessary. That allows you to convert an Object[] to a String[]. You can do the same yourself in a for loop. Surprisingly, the for loop technique often generates faster code than arraycopy. In the latest Java, arraycopy is faster except for moves of only one or two characters. arraycopy will not grow an array to hold the new elements.
You might imagine a cast from Dog[] to Dalmatian[] should be allowed if the array currently contains only Dalmatian elements. It would be an expensive check. Further, you would then have two references to the array. There would be nothing to stop you from later adding some PitBull elements via the Dog[] reference, violating the consistency requirement of the Dalmatian[] reference. That’s why the ArrayStore gotcha has to be there.
Array methods you might find useful include:
Often you want to pass an array of pairs to a constructor. Here is a trick to do that easily.
This page is posted |
http://mindprod.com/jgloss/array.html | |
Optional Replicator mirror
|
J:\mindprod\jgloss\array.html | |
Please read the feedback from other visitors,
or send your own feedback about the site. Contact Roedy. Please feel free to link to this page without explicit permission. | ||
Canadian
Mind
Products
IP:[65.110.21.43] Your face IP:[18.118.164.227] |
| |
Feedback |
You are visitor number | |