array : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

array
A fixed length block of primitives or references. Java never stores blocks of repeating structures. It always creates blocks of references to separately stored structures. 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. It won’t create any objects for you automatically.
Allocating an Array of Primitives Array Comparison
Allocating an Array of Objects Matrix Initialisation
Initialising ArrayStoreException
Passing Arrays Array Methods
Returning Arrays Gotchas
Copying and Cloning Arrays Learning More
Array to List to Collection and Back Links
Array Initialisation

Allocating an Array of Primitives

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.

Allocating an Array of Objects

The key thing to understand is initialising is a two step process:

  1. Allocate some RAM (Random Access Memory) to hold N indexable pointers, and initialise that RAM with null pointers.
  2. Fill those slots with references to some real Objects, perhaps newly allocated Objects, perhaps pre-existing ones. The slots may all point to different Objects, or some slots may point to the same Object. Java does not automatically allocate a new Object for each slot.

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.

Initialising

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 );

Passing Arrays

Methods can return arrays. Usually the callee allocates them. However the caller could allocate them and pass them as parameters.

Returning Arrays

Here are some ways from simple to complex that you can return an array of Strings from a method.

Copying and Cloning Arrays

For copying arrays you have System.array copy, Arrays. copyOf and Arrays. copyOfRange. However, ordinary loops usually generate even faster code. You can use Arrays.copyOf to convert an array of Dog objects, where each element is actually a Dalmatian object to an array of Dalmatian objects.

Array to List to Collection and Back

Array Initialisation Gotchas

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.

Array Comparison

Matrix Initialisation

In Java, a matrix is an array of arrays. Each row of the array can even have a different number of columns. It is not stored in one contiguous block

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.

ArrayStoreException

When you ask the type of an array there are three different things you might be talking about:
  1. The declared type of the array variable, e. g. Dog[] dogs;
  2. The type of the array object, e.g. Dog[] dogs = new Dalmatian[ 10 ];
  3. The type of the array element, e.g. dogs[ 0 ] = new DarkDalmatian();
These three types need not be identical. Further, they interact in subtle ways. For example, you may be able to cast an array element, where you cannot cast the array object.

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

Array methods you might find useful include:

Gotchas

Learning More

Oracle’s Javadoc on Arrays class : available:
Oracle’s Javadoc on System.arraycopy : available:
Oracle’s Javadoc on Arrays<T>.asList : available:
Oracle’s Javadoc on Arrays.binarySearch : available:
Oracle’s Javadoc on Arrays.copyOf : available:
Oracle’s Javadoc on Arrays.copyOfRange : available:
Oracle’s Javadoc on Arrays.deepEquals : available:
Oracle’s Javadoc on Arrays.fill : available:

This page is posted
on the web at:

http://mindprod.com/jgloss/array.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\array.html
logo
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.
Blog
IP:[65.110.21.43]
Your face IP:[54.83.229.102]
You are visitor number