Recipe 7.1 Using Arrays for Data Structuring


Problem

You need to keep track of a fixed amount of information and retrieve it (usually) sequentially.

Solution

Use an array.

Discussion

Arrays can be used to hold any linear collection of data. The items in an array must all be of the same type. You can make an array of any built-in type or any object type. For arrays of built-ins, such as ints, booleans, etc., the data is stored in the array. For arrays of objects, a reference is stored in the array, so the normal rules of reference variables and casting apply. Note in particular that if the array is declared as Object[], object references of any type can be stored in it without casting, although a valid cast is required to take an Object reference out and use it as its original type. I'll say a bit more on two-dimensional arrays in Recipe 7.15; otherwise, you should treat this as a review example:

import java.util.Calendar; /** Review examples of arrays: shows array allocation, processing,  * storing objects in Arrays, two-dimensional arrays, and lengths.  *  * @author Ian Darwin  * @version $Id: ch07.xml,v 1.5 2004/05/04 20:11:49 ian Exp $  */ public class Array1  {     public static void main(String[] argv) {         int[] monthLen1;            // declare a reference         monthLen1 = new int[12];        // construct it         int[] monthLen2 = new int[12];    // short form         // even shorter is this initializer form:         int[] monthLen3 = {                 31, 28, 31, 30,                 31, 30, 31, 31,                 30, 31, 30, 31,         };                  final int MAX = 10;         Calendar[] days = new Calendar[MAX];         for (int i=0; i<MAX; i++) {             // Note that this actually stores GregorianCalendar             // etc. instances into a Calendar Array             days[i] = Calendar.getInstance( );         }               // Two-Dimensional Arrays         // Want a 10-by-24 array         int[][] me = new int[10][];         for (int i=0; i<10; i++)             me[i] = new int[24];         // Remember that an array has a ".length" attribute         System.out.println(me.length);         System.out.println(me[0].length);     } }

Arrays in Java work nicely. The type checking provides reasonable integrity, and array bounds are always checked by the runtime system, further contributing to reliability.

The only problem with arrays is: what if the array fills up and you still have data coming in? See the Solution in Recipe 7.2.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net