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][]; ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.