As most of the answers here say, a Vector
stores references to objects of type Object
. If you change the underlying Object
each time you will end up with a Vector
containing lots of references to one object, which now contains the last value you gave it.
Based on the name of your variables, I'm guessing you actually want to be storing numbers in your Vector.
In an ideal world you would just add object of type int
into the Vector. Unfortunately, in Java an int
is a 'primitive type', and Vector
can only store objects of type Object
. This means you can only put Integer
objects into the Vector instead of int
objects.
So your code will look something like:
// Put a number at index 0
Integer inputNumber = new Integer(7);
numbersToCalculate.add(0, inputNumber);
// Some time later read out the value at index 0
Object objFromVector = numbersToCalculate.elementAt(0);
// Cast the Object to an Integer
Integer numberToProcess = (Integer)objFromVector;
This code will throw an IllegalCastException
if the Vector
contains something that isn't an Integer
object. If you are worried about that you can encompass it in a try
catch
statement.
In your example you will presumably want to just loop through all the numbers in the Vector. You also might want to be more prescriptive about what objects your Vector can contain (called 'Generics', which is similar to C templating). Here's what it might look like:
Vector<Integer> myVector = new Vector<Integer>();
// Add stuff to the Vector
for (Integer number : myVector)
{
// Do stuff with the number
}
The foreach
and Generics constructs were only added in Java SDK 1.5, so you can't use them if you want to run on an earlier Java SDK.