Arrays

An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information.

One-Dimensional Arrays

A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is

type var-name[];

int month_days[];

type declares the base type of the array. you must allocate one using new and assign it to month_days. new is a special operator that allocates memory.

array-var = new type[size];

month_days = new int[12];

Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and array-var is the array variable that is linked to the array.

Putting together all the pieces, here is a program that creates an array of the number of days in each month.

// Demonstrate a one-dimensional array.

class Array {

public static void main(String args[]) {

int month_days[];

month_days = new int[12];

month_days[0] = 31;

month_days[1] = 28;

month_days[2] = 31;

month_days[3] = 30;

month_days[4] = 31;

month_days[5] = 30;

month_days[6] = 31;

month_days[7] = 31;

month_days[8] = 30;

month_days[9] = 31;

month_days[10] = 30;

month_days[11] = 31;

System.out.println(“April has ” + month_days[3] + ” days.”);

}

}

This program generates the following output:

April has 30 days.

When you run this program, it prints the number of days in April. As mentioned, Java array indexes start with zero, so the number of days in April is month_days [3] or 30.

Arrays can be initialized when they are declared. The process is much the same as that used to initialize the simple types. An array initializer is a list of comma-separated expressions surrounded by curly braces.

// An improved version of the previous program.

class AutoArray {

public static void main(String args[]) {

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };

System.out.println(“April has ” + month_days[3] + ” days.”);

}

}

Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called twoD.

int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int.

// Manually allocate differing size second dimensions.

class TwoDAgain {

public static void main(String args[]) {

int twoD[][] = new int[4][];

twoD[0] = new int[1];

twoD[1] = new int[2];

twoD[2] = new int[3];

twoD[3] = new int[4];

int i, j, k = 0;

for(i=0; i<4; i++)

for(j=0; j<i+1; j++) {

twoD[i][j] = k;

k++;

}

for(i=0; i<4; i++) {

for(j=0; j<i+1; j++)

System.out.print(twoD[i][j] + ” “);

System.out.println();

}

}

}

This program generates the following output:

0

1 2

3 4 5

6 7 8 9

Enumeration

The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superseded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes (such as Vector and Properties), is used by several other API classes, and is currently in widespread use in application code.

Enumeration specifies the following two methods:

boolean hasMoreElements( )

Object nextElement( ) 

When implemented, hasMoreElements( ) must return true while there are still more elements to extract, and false when all the elements have been enumerated. nextElement( ) returns the next object in the enumeration as a generic Object reference. That is, each call to nextElement( ) obtains the next object in the enumeration. The calling routine must cast that object into the object type held in the enumeration.

Here are some enumeration methods and its descriptions:

Enumeration elements (): Returns an enumeration of the values contained in the hash table.

Enumeration keys(): Returns an enumeration of the keys contained in the hash table.

Enumeration propertyNames(): Returns an enumeration of the keys. This includes those keys

found in the default property list, too.

Enumeration getApplets():Returns an enumeration that contains all of the applets within the current applet context.

Enumeration getInitParameterNames( ): Returns an enumeration of all initialization parameter names.

Hashtable

Hashtable was part of the original java.util (contains common utilities) and is a concrete implementation of a Dictionary (abstract class that represents a key/value storage repository and operates much like Map). However, Java 2 reengineered Hashtable so that it also implements the Map interface. Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but is synchronized.

Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

A hash table can only store objects that override the hashCode( ) and equals( ) methods that are defined by Object. the most common type of Hashtable uses a String object as the key. String implements both hashCode( ) and equals( ). The Hashtable constructors are shown here:

Hashtable( )

Hashtable(int size)

Hashtable(int size, float fillRatio)

Hashtable(Map m)

The first version is the default constructor. The second version creates a hash table that has an initial size specified by size. The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill ratio, then 0.75 is used. Finally, the fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used. The fourth constructor was added by Java 2.

The following example reworks the bank account program, shown earlier, so that it uses a Hashtable to store the names of bank depositors and their current balances:

// Demonstrate a Hashtable

import java.util.*;

class HTDemo {

            public static void main(String args[]) {

                        Hashtable balance = new Hashtable();

                        Enumeration names;   

                        String str;

                        double bal;

                        balance.put(“John Doe”, new Double(3434.34));

                        balance.put(“Tom Smith”, new Double(123.22));

                        balance.put(“Jane Baker”, new Double(1378.00));

                        balance.put(“Todd Hall”, new Double(99.22));

                        balance.put(“Ralph Smith”, new Double(-19.08));

                        // Show all balances in hash table.

                        names = balance.keys();

                        while(names.hasMoreElements()) {

                                    str = (String) names.nextElement();

                                    System.out.println(str + “: ” +

                                    balance.get(str));

                        }

                        System.out.println();

                        // Deposit 1,000 into John Doe’s account

                        bal = ((Double)balance.get(“John Doe”)).doubleValue();

                        balance.put(“John Doe”, new Double(bal+1000));

                        System.out.println(“John Doe’s new balance: ” +

                        balance.get(“John Doe”));

            }

}

The output from this program is shown here:

Todd Hall: 99.22

Ralph Smith: -19.08

John Doe: 3434.34

Jane Baker: 1378.0

Tom Smith: 123.22

John Doe’s new balance: 4434.34

One important point: like the map classes, Hashtable does not directly support iterators. Thus, the preceding program uses an enumeration to display the contents of balance.