Question

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.

Was it helpful?

Solution

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");
            }
        };
    }

OTHER TIPS

Vecotr class does not implement Enumeration. Where did you see that, can you share source of you information.

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

Further, none of the the class or interface implement or extend Enumeration interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top