我对 vector 类的枚举接口(interface)深感困惑。我知道现在不再用于存储和搜索,但仍然对它们感兴趣。
我所知道的事实:
Vector 类实现了 Enumeration 接口(interface),因此它的方法
hasMoreElements()
和nextElement()
。Vector 类有一个方法
elements()
,它返回 Vector 类的对象,因此其返回类型为 Enumeration。
我感到困惑的事情:
假设 vector vec=new Vector(2,3)
;
vec.elements().nextElement()
给了我想要的对象,而 vec.nextElement()
是未定义的,尽管 Vector 类实际上实现了枚举接口(interface),所以为什么它的对象不能直接访问被覆盖的方法。
最佳答案
JAVA DOC of Vector类显示该类中实现的接口(interface)是 Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
vector 的elements()
方法签名为:public Enumeration<E> elements()
调用
返回 instance of implemented Enumeration
从以下源代码可以明显看出:
public Enumeration<E> elements() {
return new Enumeration<E>() { // return implemented enumeration
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() { // implementing nextElement
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
// accessing vector elements data which
//traverses an array of object
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
关于java - 枚举接口(interface)和 vector 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467161/