给出
private final Vector v = new Vector(); //instance variable
以下3行是同一类中的实例方法。
1. int length = v.capacity();
2. int size = v.size();
3. Object o = v.getElementAt(0);
我在第3行得到ArrayIndexOutOfBoundsException
。
调试器显示Vector
有10个元素
length
显示10
size
显示0
。
为什么会抛出此异常,我是否需要setSize()
使用Vector v
?
答案 0 :(得分:2)
不,但你必须在获得之前添加一个元素。
Vector是老派Java 1.0。它使用同步化作为其默认值,这可能会影响您的性能。你为什么不考虑更新的java.util.List和java.util.ArrayList类?
答案 1 :(得分:2)
在必须增加容量之前,capacity()方法告诉您Vector可以使用许多元素。它并没有告诉你当前在Vector中有很多元素,这就是指定要执行的size()。在你的情况下确实如此,因为Vector是空的。
您可以通过为构造函数提供参数来指定容量:
Vector v = new Vector(20);
/* This vector will have the starting capacity
of 20 elements, before it has to increase
its capacity */
Vector v = new Vector(10, 5);
/* This vector will have an initial capacity
of 10 elements, and when it overflows the
second parameter tells the vector to increase
its capacity by 5. */
修改强>
根据您对其他帖子的评论,您的应用程序中似乎有两个主题 - 其中一个将内容放入向量中,另一个内容读取向量?
然后你必须添加一个控制结构来检查向量是否为空,然后再尝试从中获取元素。
肮脏的例子:
/* Vector instantiation goes here */
boolean keepRunningFlag = true;
while(keepRunningFlag) {
if (!vector.isEmpty()) {
Object o = vector.remove(vector.size() - 1);
keepRunningFlag = doStuffWithVectorElement(o);
}
}
答案 2 :(得分:1)
没有。该向量为10个元素预留了空间。但是它还没有包含使用'put'
向向量添加内容所需的任何元素长度会告诉你预留空间的数量,大小会告诉你实际可以使用多少。
向量通常会保留比优化所需的空间更多的空间
答案 3 :(得分:1)
容量是为当前和未来元素分配的空间,是由于性能原因而暴露的内部(向量)数字。容量等于或大于它包含的元素数量。
size()显示您在向量中放置了多少元素。容量更多地是向量的内部簿记性质。你只能从向量中获取元素0 ... getSize() - 。
也就是说,如果你不在多个线程中使用数据,那么最好使用ArrayList。
你可以使用isEmpty()检查向量是否为空,这应该像getSize()== 0那样。
答案 4 :(得分:1)
正如几位人士所提到的,你不想看看Vector的容量,或者(等效地)它的内部数组的长度。在实践中,您几乎从不想要查看Vector的容量。你需要使用size()(或isEmpty(),当且仅当size()返回0时才返回true。)
尝试在不存在的元素上调用getElementAt(x)不会返回null。它引发了一个例外。
由于你有另一个插入元素的线程,你可能想要检查大小并以原子方式检索元素。实际上,这听起来像是在尝试实现生产者/消费者队列,在这种情况下,您还希望将元素作为同一原子操作的一部分进行删除。最直接的方法是在Vector上进行同步。例如:
Object o = null;
synchronized(v) {
if (!v.isEmpty()) {
o = v.getElementAt(0);
v.removeElementAt(0);
}
}
// at this point the first element of the vector will be removed
// (if there was one) and o be pointing at that first element. If
// the Vector was empty, o will still be null.
使用此代码的一些注意事项: