ARRAYS OF ARRAYS

CONTENTS

1. Overview
2. Example program


1. OVERVIEW

From the work on arrays we have seen that we usual declare the size of the array prior to run time. Using the dynamic array concept we can of course delay this declaration till run time, but the size of the array is always fixed once it has been declared. An alternative data structure, known as a vector, will allow for data items to be stored in an array like structure but without having to declare its length. On declaring a vector we specify an initial size which is automatically doubled whenever we run out of space.

The Java API includes a class vector contained in the java.util package.



2. EXAMPLE

Consider the code given in Table 1.

// VECTOR EXAMPLE
// Frans Coenen
// 10 February 2000
// Dept Computer Science, University of Liverpool

import java.util.*;
// import java.io.*;

class VectorExample{

    // ------------------- FIELDS ------------------------ 
    
    private static final int INITIAL_SIZE = 4;
    private static final int INDEX_MAXIMUM = 20;  
    private static Vector myVector;     
		      
    // ------------------ METHODS ------------------------  
    
    /* Main method */
    
    public static void main(String[] args) /* throws IOException */ {
        int n1, n2;
                   
	// Crerate an instance of the class Vector
	
	myVector = new Vector(INITIAL_SIZE);
	
	// Load vector
	
	loadVector();
	
	// Trim vector
	
	trimVector();
	
	// Output vector
	
	outputVector();
	
	// Index of 10
	
	indexOf(10);
	
	// Change element
	changeElement(9,10);
	changeElement(13,10);
	changeElement(19,10);
	changeElement(20,10);
	
	// Indexes of 10
	
	indexesOf(10);
	
	// Add to vector
	
	addToVector(40);
	outputVector();
	}
	
    /* Load vector method */
    
    public static void loadVector() {
        System.out.println("LOAD VECTOR");
	
	// Loop
	
	for (int index=0;index < INDEX_MAXIMUM;index++) {		             
            myVector.addElement(new Integer(index*2));
	    System.out.println("(" + index + ") Element = " + myVector.elementAt(index).toString() + 
	    		", Capacity = " + myVector.capacity() +
			", Size = " + myVector.size());
	    }
	}
	
    /* trim vector method */
    
    public static void trimVector() {
        
	System.out.println("\nTRIM VECTOR");
	myVector.trimToSize();

	// Output
	
	System.out.println("Capcity = " + myVector.capacity() + ", size = " + 
			myVector.size());
	System.out.println("First Element = " + myVector.firstElement() + 
			", Last Element = " + myVector.lastElement());
    	}
	
    /* Output vector method */
    
    public static void outputVector() {
        System.out.println("\nOUTPUT VECTOR");

	// Loop
	
	for (int index=0;index < myVector.size();index++)	{	             
	    System.out.print(myVector.elementAt(index).toString() + " ");
	    }
	System.out.println();
	}
    
    /* Index of method */
    
    public static void indexOf(int element) {
        System.out.println("\nINDEX OF");
	
        System.out.println("Index of element equivalent to " + element + " is " +
			myVector.indexOf(new Integer(element)));
	}
	
    /* Change element method */
    
    public static void changeElement(int index, int element) {
        System.out.println("\nCHANGE ELEMENT");
	
    	if (index >= 0 && index < myVector.size()) 
			myVector.setElementAt(new Integer(element),index);
        else System.out.println("Index " + index + " out of range!");
	}	
	
    /* Indexes of method */
    
    public static void indexesOf(int element) {
	int index = 0, total =0;
	
	System.out.println("\nINDEXES OF");
	
	// Loop
	
	while (index != -1) {
	    index = myVector.indexOf(new Integer(element),index);
	    if (index != -1) {
	     	System.out.print(index + " ");
		total++;
	        index++;
		}
	    }
	     
	// End
	 
	System.out.println();
	System.out.println("Number of occurances of the element " + element +
			" is equal to " + total);
        }

    // Add to vector method
    
    public static void addToVector(int element) {
        
	System.out.println("\nADD TO VECTOR");
	
        myVector.addElement(new Integer(element));
	System.out.println("Element = " + element + 
	    		", Capacity = " + myVector.capacity() +
			", Size = " + myVector.size());
        }
    }

Table 1: Vector example code

Notes

  1. In the main method we create a new isntance of the class vector. The initial size of the vector is given by the constant INITIAL_SIZE which is set to 4. Note that the instance is a static private instance of the class.
  2. In the loadVector method elements are added to the vector using a for loop. A number of instance methods from the Vector class are used here:
  3. The void trimVector() "trims" the capacity of the vector to be equal to its size. This is done using the trimToSize() method. Note that subsequent addition to the vector will cause it to grow again (initially by doubling the current size). The method also includes calls to the firstElement() and lastElement() methods in the vector class.
  4. The outputVector() method outputs the contents of the vector by looping through it until the index equals the size of the vector as returned by the size() method. Use is also made of elementAt(int index) method to access indivaidual elements and the toString() to convert the resulting object to a string.
  5. The following method (indexOf(int element)) uses a Vector class method of the same name to access a particular object. Note that we convert the integer input argument to be an instance of the Integer wrapper class.
  6. The changeElement illustrates the use of the setElementAt(Object obj,int index) method which places the given ovject at the given index. This throws an IndexOutOfBoundsException if the given index is larger than the current size, so the method uses the sdiz() methid to terst whether the given index is within range.
  7. The indexesOf(int element) method is similar to the indexOf method described earlier except that the search is started at a given index. This is facilitated by the indexOf(Object obj, int index) method. This allows us, as in this case, to count the number of occurances of a given element. Note that when we have found an element we increment the returned index by one to otherwise the same element will be found at infinitem.
  8. The final method (addToVector(Object obj)) serves to show that we can continue adding to the vector even though it has been "resized".

Some sample output produced by the above code is given in Table 2.

java VectorExample
LOAD VECTOR
(0) Element = 0, Capacity = 4, Size = 1
(1) Element = 2, Capacity = 4, Size = 2
(2) Element = 4, Capacity = 4, Size = 3
(3) Element = 6, Capacity = 4, Size = 4
(4) Element = 8, Capacity = 8, Size = 5
(5) Element = 10, Capacity = 8, Size = 6
(6) Element = 12, Capacity = 8, Size = 7
(7) Element = 14, Capacity = 8, Size = 8
(8) Element = 16, Capacity = 16, Size = 9
(9) Element = 18, Capacity = 16, Size = 10
(10) Element = 20, Capacity = 16, Size = 11
(11) Element = 22, Capacity = 16, Size = 12
(12) Element = 24, Capacity = 16, Size = 13
(13) Element = 26, Capacity = 16, Size = 14
(14) Element = 28, Capacity = 16, Size = 15
(15) Element = 30, Capacity = 16, Size = 16
(16) Element = 32, Capacity = 32, Size = 17
(17) Element = 34, Capacity = 32, Size = 18
(18) Element = 36, Capacity = 32, Size = 19
(19) Element = 38, Capacity = 32, Size = 20

TRIM VECTOR
Capcity = 20, size = 20
First Element = 0, Last Element = 38

OUTPUT VECTOR
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38

INDEX OF
Index of element equivalent to 10 is 5

CHANGE ELEMENT

CHANGE ELEMENT

CHANGE ELEMENT

CHANGE ELEMENT
Index 20 out of range!

INDEXES OF
5 9 13 19
Number of occurances of the element 10 is equal to 4

ADD TO VECTOR
Element = 40, Capacity = 40, Size = 21    

OUTPUT VECTOR
0 2 4 6 8 10 12 14 16 10 20 22 24 10 28 30 32 34 36 10 40  

Table 2: Sample output generate from vector example code given in Table 1




Created and maintained by Frans Coenen. Last updated 11 February 2000