Java arrays

I didn’t know this until very recently, but in Java, arrays of arrays can have rows of unequal sizes. For example, say you want to create a lower triangular matrix of integers called lowerTri consisting of 10 rows with each row having 1, 2, 3,…, 10 elements. This is perfectly legal in Java:

int[][] lowerTri;
lowerTri = new int[10][];  // allocate memory for 10 rows of arbitrary length
 for (int r=0; r<lowerTri.length; r++) {
     // set the number of elements in each row to the 
     // r+1 since it's lower triangular
     lowerTri[r] = new int[r+1];
 }
 
 // print the resulting array 
 for (int r=0; r<lowerTri.length; r++) {
     System.out.print("\nRow "+r+" has "+lowerTri[r].length+" elements:");
     for (int c=0; c<lowerTri[r].length; c++) {
         System.out.print(" " + lowerTri[r][c]);
     }
     System.out.println("");
 }

Think of all the memory saved when you know your matrix is symmetric, or if you want to create something akin to a stem-and-leaf plot (with each row consisting of an array of observations).

Nice!

Advertisements

2 thoughts on “Java arrays

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s