Main Content

Java arrays - are they true arrays or not?

Archive - Originally posted on "The Horse's Mouth" - 2010-02-23 23:52:23 - Graham Ellis

Java's arrays are "true" arrays, in that they occupy sequential memory locations in which they are looked up by position number, so that access can be very fast. But that does mean that once an array has been defined to be a certain size, it cannot be resized in situ.

Fortunately, Java is a dynamically running language, with variables being created, used, released and garbage collected (so that memory is available for reuse within the same process) as the program runs - so you don't have to decide how big each of your arrays needs to be at the time you compile your program.

On our Java Bootcamp training course, I set an exercise that uses this reuse capability in a practical way - in Pascal's triangle, each row can be derived from the previous row and each row contains one more element than the previous row. So, we start off initialising previous and to nothing and declaring current:
  int [] current;
  int [] previous = {};

then, within a loop we define current as being one longer than previous:
  current = new int[previous.length+1];
we then do the calculations to work out the new values, and at the end of the loop we take the new array (current) and also apply the previous name to it - in the process, releasing the previous previous for garbage collection:
  previous = current;

The full source code of this example is [here].

Java does not (strictly) support two dimensional arrays - where each of the one dimensional arrays is arranged sequentially in memory directly after the previous one. Rather, it supports arrays of arrays. This might sound like a semantic difference, but it's of great use. For a tiny reduction in efficiency in accessing rectangular blocks of data, the programmer gains the ability to do everything he could using true 2 dimensional arrays within the language, AND the ability to create arrays which are differently shaped - as (for example) in another implementation of Pascal's Triangle.

The enclosing array is set up as follows:
  int [][] tri = new int[20][];
and then each row is set up to a differing length in a way that is not possible with true 2 dimensional arrays:
  for (int r=0; r<tri.length; r++) {
  tri[r] = new int[r+1];

There's a full source code example here [here].