Data Structuring Using Arrays

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[], then object references of any type can be stored in it without casting, though 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 Section 7.17; otherwise, you should treat this as a review example.

import java.util.*;
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? Solution in Section 7.3.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.197.251