Home | FAQ | Contact me

Java Arrays

This is a collection of cool things to do with arrays as they are encountered and I get excited enough to write them down. (I'm getting long enough in the Java tooth that I don't always recognize when I should note something for general interest.)

Variable- or unknown-length arrays

When faced with creating an array, especially a complex one with references to class instances, etc., you can resort to ArrayList. Prior to Java 1.5, ArrayList held an array of Object (and still does). Since Java 5 and generics, it's been possible to give type to ArrayList. In fact, Java will warn unless you do (or unless you turn off these warnings).

From what I've seen in the debugger, declaring a variable of ArrayList and putting at least one element into it results in the allocation of such an array with some extra room in it, in anticipation of more being added. Here's the lifecycle of such an array:

  1. Declare an array ready to hold a few references to object of class Type.
  2.  
  3. Add references into the array using the add() method. These will fill out the subscripts, reallocating (and copying) the array as needed. This is a speed consideration: you must know your data. If you have any idea how long the array will ultimately be, you're better off using a simple array directly or, at least, presizing ArrayList to the best of your ability.
  4.  
  5. Convert the ArrayList into an array of Object. You cannot cast it to Type[] unfortunately as to do this will result in a ClassCastException. (There's probably more to say here and I'll come back one day to say it.)
  6.  
  7. Consume the array elements by casting each.
public class Type
{
	.
	.
	.
	// 1. Declare an array...
	ArrayList< Type > array = new ArrayList< Type >();
	.
	.
	.
	// 2. Add references...
	Type t = new Type();

	array.add( t );
	.
	.
	.
	// 4. Consume the array one subscript at a time...
	Object[]  oa  = array.toArray();
	int       len = array.length;

	for( int i = 0; i < len; i++ )
	{
		// 3. Convert to the desired type...
		Type  tt = ( Type ) oa[ i ];

		System.out.println( tt.toString() );
	}

Important note: this scheme works only for objects; it will not work for intrinsic, primitive types such as int, long, boolean, etc. You must instead use Integer, Long, etc.

Printing out contents of arrays

It should surprise you that using the toString() method doesn't always do what you might think it will.

import java.util.Arrays;

public class Grunge
{
	public static void main( String[] args )
	{
		String[]	string = { "this", "is", "a", "test" };

		// nope, this doesn't work...
		System.out.println( "Our string is " + string.toString() );

		// here's the trick!
		System.out.println( Arrays.toString( string ) );
	}
}

The output from this experiment is:

Our string is [Ljava.lang.String;@3e25a5 [this, is, a, test]