Multi-Dimensional Arrays

We can expand the whole idea of arrays to multiple dimensions, beyond one or two dimensions. Read these sections to see how this is done.

From the Java Library: java.uti

The java.util.Vector class implements an array of objects that can grow in size as needed. One limitation of regular arrays is that their lengths remain fixed. Once the array is full – once every element is used – you can't allocate additional elements. 

The Vector class contains methods for storing and retrieving objects, and for accessing objects by their index position within the Vector (Fig. 9.27). 

Vector
 
+ Vector()
+ Vcclor(in size : int)
+ addElcment(in o :Object)
+ ckmcntAt(in index : int) :Object
+ inscrtElcmentAt(in o :Object, in x : int) 
+ indcxOf(in et :Object) : int
+ IastlndcxOf(in o :Object) :int
+ rcmoveElementAt(in index : int) 
+ sizc( ) : int

Vector Figure 9.27: The java.util.Vecto

One use for a Vector would be when a program needs to store input from the user or a file without knowing in advance how many items there are. Using a Vector is less efficient than an array in terms of processing speed, but it gives you the flexibility of growing the data structure to meet the storage requirements. 

As an illustration of this idea, the program in Figure 9.28 creates a random number of integers and then stores them in a Vector. The Vector, which is declared and instantiated in main(), is initially empty. Integers from 0 to the random bound are then inserted into the Vector. In this case, insertions are done with the addElement() method, which causes the Vector object to insert the element at the next available location, increasing its size, if necessary.

Once all the integers have been inserted, the printVector() method is called. Note that it uses the size() method to determine how many elements the Vector contains. This is similar to using the length() method to determine the number of characters in a String.

Finally, note that a Vector stores objects. It cannot be used to store primitive data values. You cannot store an int in a Vector. Therefore, we need to use the Integer wrapper class to convert ints into Integers before they can be inserted into the Vector. Because you can't just print an Integer, or any other Object, the toString() method is used to print the string representation of the object.

By defining Vector to store Objects, Java's designers have made it as general as possible and, therefore, as widely useful as possible.


JAVA EFFECTIVE DESIGN Generality. Defining a data collection, such as an array or a Vector, in terms of the Object class makes it capable of storing and processing any type of value, including values of primitive data types. This is because the Object class is the root of the Java class hierarchy.