枚举接口和向量类

时间:2013-10-19 14:32:52

标签: java oop vector enumeration

我对Enumeration接口和矢量类感到非常困惑。我知道现在还没有用于存储和搜索,但仍然对它们感兴趣。

事实我知道:

  1. Vector类实现了Enumeration接口,因此实现了方法hasMoreElements()nextElement()

  2. Vector类有一个方法elements(),它返回Vector类的对象,因此返回类型为Enumeration。

  3. 我很困惑:

    假设Vector vec=new Vector(2,3); 虽然Vector类实际上实现了Enumeration Interface,但vec.elements().nextElement()给了我所需的对象,而vec.nextElement()只是{{1}}未定义,所以为什么它的对象可以直接访问被覆盖的方法。

2 个答案:

答案 0 :(得分:1)

Vecotr类未实现Enumeration。您在哪里看到的,是否可以与您分享信息来源。

public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable

此外,类或接口都没有实现或扩展Enumeration接口。

答案 1 :(得分:1)

JAVA DOC of Vector类显示此类中实现的接口为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");
            }
        };
    }
相关问题