chetan mehta chetan mehta -4 years ago 94
Java Question

Enumeration Interface and vector Class

I am deeply confused about the Enumeration interface an vector class. I know there aren't used for storing and searching now a days but still was interested in them.

Facts I know:


  1. Vector class implements Enumeration interface and thus its method
    hasMoreElements()
    and
    nextElement()
    .

  2. Vector class has a method
    elements()
    that returns an object of Vector class therefore has its return type of Enumeration.



Thing I am Confused about:

Suppose
Vector vec=new Vector(2,3)
;
vec.elements().nextElement()
gives me desired object whereas just
vec.nextElement()
is undefined though Vector class actually implements Enumeration Interface so why can't its object directly access the overridden methods.

Answer Source

The JAVA DOC of Vector class shows that implemented interfaces in this class are Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess

The Vector's elements() method signature is: public Enumeration<E> elements() calling Which returns an instance of implemented Enumeration as is evident from following source code:

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");
            }
        };
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download