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.)
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:
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.
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]