正如这里的大多数答案所说, aVector
存储对 type 对象的引用Object
。Object
如果您每次更改底层证券,您最终会得到一个Vector
包含大量对一个对象的引用,该对象现在包含您给它的最后一个值。
根据变量的名称,我猜您实际上希望将数字存储在 Vector 中。
在理想的世界中,您只需将类型的对象添加int
到 Vector 中。不幸的是,在 Java 中 anint
是一种“原始类型”,并且Vector
只能存储 type 的对象Object
。这意味着您只能将Integer
对象而不是对象放入 Vector 中int
。
所以你的代码看起来像:
// 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;
IllegalCastException
如果Vector
包含不是Integer
对象的东西,此代码将抛出一个。如果您担心这一点,您可以在try
catch
声明中包含它。
在您的示例中,您可能只想遍历 Vector 中的所有数字。您可能还希望对 Vector 可以包含哪些对象(称为“泛型”,类似于 C 模板)更加规范。下面是它的样子:
Vector<Integer> myVector = new Vector<Integer>();
// Add stuff to the Vector
for (Integer number : myVector)
{
// Do stuff with the number
}
和foreach
泛型结构仅在 Java SDK 1.5 中添加,因此如果您想在早期的 Java SDK 上运行,则不能使用它们。