I like to think of objects of type Vector in the same way that I think of vectors in mathematics. Namely a vector in mathematics is an ordered pair (x,y). Well, actually this is a vector in 2 dimensions. In three dimensions, our vector could be represented as (x,y,z). In fact, even in mathematics we can talk about vectors in n dimensions, and we would represent such a thing as:
This is called an n-tuple, but don't worry too much about the name. The point is that it is a set of things that are listed in a certain order. In math, the things are all of the same type -- real numbers for example, or possibly integers.
In Java, we can think of the Vector in a similar manner: it is an ordered list of things, and like the mathematical vector, it can have any number of these things in it. We call these things elements of the Vector. In Java, the elements can appear to be of different types, but in fact they are all of the same type. They are all references; in fact they are all references to instantiations (objects) of type Object.
Yes, that's right. There's a class called Object, and it turns out that every single object that we instantiate has type Object. This is due to inheritance, which we spoke about briefly before, and which we'll describe in more detail very soon. The important thing to remember is that the Vector stores an ordered set of references to any types of object.
Here are some basic Vector rules:
And here are some of the methods of the class Vector: (take a look at the API for more)
addElement(Object O) clear() elementAt(int index) remove(int index) int size() setElementAt(Object O, int index) insertElementAt(Object O, int index);
Vector v = new Vector(); Student s = new Student(``Fred''); v.addElement(s); v.addElement(``hi''); v.addElement(``there'');
How would you picture the above Vector after each line? How would you print out the elements of the Vector? How would you use the above methods to manipulate the Vector?
The reason for rule 5 is that every reference which is stored in a Vector is of type Object. Even though we know more specific information about the type, the Vector object doesn't, so when we retrieve something from a Vector it comes to us as something of type Object. If we want to use methods that are not in the class Object with our object, then we must cast it to the appropriate type.