Vectors
Vectors are like arrays that can be as large as you need them to be - they grow if necessary. They also update easily.
| Function | Arrays | Vectors |
| Library Needed | - | import java.util.Vector; |
| Declaration | int array[]=new int[20]; max size of 20! |
Vector a = new Vector (20); can have more than 20. Note different brackets. |
| Adding an element | array[2]=45; you must know the index where you want to add it. |
a.addElement (45); if position doesn't matter a.insertElementAt(45, 2); if it does. |
| Removing an element | array[2]=0; and shuffle all other elements down. requires a loop | a.removeElement (45); finds the first instance of 45, removes it and shifts other elements down. |
| Loop to print all elements | for (int i = 0 ; i < array.length ; i++) { System. out.println (array[i]); } note the length variable and the brackets []. |
for (int i = 0 ; i < a.size () ; i++) { System.out.println (a.elementAt (i)); } note the size variable and the brackets ( ). |
Vectors with Objects
Assume you have the following class:
public class Person
{ String lname;
String fname;
int year;
}
To declare a vector you would write:
Vector a = new Vector (20);
This doesn't mention the type, or anything!
To add an item to a vector, create a variable, construct it, fill it and add it to the vector. Note: for each new element in the vector, you must call the new command again.
Person x = new Person();
x.lname = "Gosling";
x.fname = "James";
x.year = 1995;
a.addElement(x);
To print out a vector of people:
Person temp = new Person ();
for (int i = 0 ; i < a.size () ; i++)
{
temp = (Person) a.elementAt (i); //pull off one Person
System.out.println (temp.lname);
System.out.println (temp.fname);
System.out.println (temp.year);
}
You must cast when you pull an element off a vector (the (Person) above in the code). This is because vectors store items that are Objects. Objects are the "mother of all classes". Everything in java is descended from an Object. Thus, everything else can be stored in a vector. While there, it "forgets" what type it is and must be reminded when it comes out by casting.