Home Search Contact us About us
Title Introduction to Collections and Arrays
Summary How and when to use collections and arrays.
Contributor John McTainsh
Published 27-Oct-2000
Last updated 27-Oct-2000
Page rating   46% for 3 votes Useless Brilliant

Description.

Arrays and collections are simple ways to store sets of data. Arrays are more suited to simple known size groups. Collections are better for things that are more dynamic in size and need to be searched or ordered.

Simple one dimensional array.

Declare an array using the [] operator. Then use new to allocate the memory and size for the array. You can use arrays with objects and primitive data types in the same manner. One handy thing to note is the .length attribute contains the length of the array (one more than the last index value).
import java.lang.Math;
...
    //Declare and populate the array
    double aryScore[] = new double [16];
    for( int n = 0; n < aryScore.length; n++ )
        aryScore[n] = Math.sqrt( n );
        
    //Display the array
    for( int n = 0; n < aryScore.length; n++ )
        System.out.println( aryScore[n] );

Multi dimensional array.

This first example shows a simple rectangular array.

    //Rectangular 3 x 2 array
    int aryPlain [][] = { { 1,  2,  3 },
                          { 4,  5,  6 } };
    for( int nRow = 0; nRow < aryPlain.length; nRow++ )
    {
        System.out.println();
        for( int nCol = 0; nCol < aryPlain[nRow].length; nCol++ )
            System.out.print( aryPlain[nRow][nCol] + " " );
    }

This example shows a jaggard array. Note each row is a different length.

    //Jaggered array
    aryPlain = new int [][] { { 1,  2,  3, 5, 6, 7, 8, 9 },
                              { 1 },
                              { 1,  2,  3, 5 },
                              { 1,  2,  3, 5, 6, 7 } };
    for( int nRow = 0; nRow < aryPlain.length; nRow++ )
    {
        System.out.println();
        for( int nCol = 0; nCol < aryPlain[nRow].length; nCol++ )
            System.out.print( aryPlain[nRow][nCol] + " " );
    }

The last example shows a three dimensinal array that is declared and populated as we go.

    //Three dimensional array declared as we go
    int aryXYZ[][][];
    aryXYZ = new int [5][][];
    for( int nX = 0; nX < aryXYZ.length; nX++ )
    {
        aryXYZ[nX] = new int[3][];
        for( int nY = 0; nY < aryXYZ[nX].length; nY++ )
        {
            aryXYZ[nX][nY] = new int[10];
            for( int nZ = 0; nZ < aryXYZ[nX][nY].length; nZ++ )
                aryXYZ[nX][nY][nZ] = nX*nY*nZ;
        }                
    }
...
    //Display X x Y and Z total
    for( int nX = 0; nX < aryXYZ.length; nX++ )
    {
        System.out.println();
        for( int nY = 0; nY < aryXYZ[nX].length; nY++ )
        {
            int nTotal = 0;
            for( int nZ = 0; nZ < aryXYZ[nX][nY].length; nZ++ )
                nTotal += aryXYZ[nX][nY][nZ];
            DecimalFormat df = new DecimalFormat( "000" );
            System.out.print( df.format(nTotal) + "  " );
        }
    }

Collections.

JDK 1.0 to JDK 1.2. Somebody just don't seem to be able to get collections right. As each new version of the language arrives a new set of names comes out for collections and other methods are added and Deprecated. This example seems to work with VJ++ using java 1.1.4. But now Vector has been replaced with ArrayList so check the documentation and ensure JVM supports the commands you are using.

There are three types of collections.

interface

concrete class

Allow Duplicates

Ordered

Collection  

Yes

No

Set HashSet

No

Yes

List ArrayList(LinkedList)

Yes

Yes

Map (HashMap)

A HashMap is a collection of key and value pairs so items can be quickly located using the key.

Vector (ArrayList)

In this examplle the list is populated with an unknown at compile time number of items. Later the elements are recalled and displayed. JDK 1.2 would use add and get to insert and retrieve the data.

import java.lang.Math;
import java.util.Vector;
...
    //Populate the collection
    Vector listSquareRoots = new Vector();
    int nSquare = 0;
    double dRoot;
    do
    {
        dRoot = Math.sqrt( nSquare++ );
        listSquareRoots.addElement( new Double(dRoot) );        
    } while( dRoot < 4.0 );

...
    
    //Display the collection
    for( int n = 0; n < listSquareRoots.size(); n++ )
        System.out.println( (Double)listSquareRoots.elementAt( n ) );

Enumeration / Iterators.

Enumeration has now been replaced with Iterator in JDK 1.2. As time goes by this will probably change again so check your target platform before using the latest class.

The following code uses the an iterator to move through the list populated in the previous example.

import java.util.Enumeration;
...
    //Display the list using an iterator
    Enumeration enum = listSquareRoots.elements();
    while( enum.hasMoreElements() )
        System.out.println( (Double)enum.nextElement() );
Comments Date
Home Search Contact us About us