.Tutorial # 9.

Differences Between Arrays and Vectors


			|	Array a			Vector v
---------------------------------------------------------------------
Element Type		|	established by		reference to object
			|	declaration of a
			|	
Element referenced by	|	a[index]		v.elementAt(index)
			|	
Element assigned by	|	a[index] = value	v.setElement(value)
			|	
Number of Elements	|	a.length		v.size()
			|
Can store primitive	|	YES			NO
data types?		|
			|
Can grow dynamically	|	NO			YES
			|	
Defined by		|	Java language		Java class library
Arrays


    An array is not a class, it is built into the language itself. There are no array methods, but there is a field 'length' that is the length of the array. They can hold primative values, as well as references to objects. The type that the array is to store must be declared at the time the array is declared. Arrays cannot grow past the size that it is declared to.

Arrays are created as follows:
int x;
int[] variableName = new int[x];

Where x is the maximum size. When you are referencing an array, the counting starts from 0, yet when you initialize it, you specify how many items the array can store (x), which starts counting from 1.

Vectors


The key benefit of Vectors, is that they do not need to have a maximum size declared when the vector is declared, hence they are limitless in there size (provided that the computer has enough room for storage). They only hold references to objects, not to primative values. There are many provided methods for working with vectors, and they go as follows.

Vector v = new Vector() - declares a Vector object

myVector.hasMoreElements() - returns true if there are more elements in the vector, false otherwise.

myVector.next() - returns a pointer to the next object in the vector

myVector.elementAt(index) - returns a pointer to the object in the vector at the position index

myVector.insertElementAt(object, index) - returns a pointer to the next object in the vector

myVector.removeElementAt(index + 1) - removes an Object at the position index + 1

myVector.addElement(anObject) - adds anObject to the end of the vector

myVector.size() - returns the size of the vector (counting from 1)


sitemap