Java collection iterator

How we are able to create objects of Enumeration, Iterator, ListIterator since they are interfaces. Iterator itr=v.iterator();//where v is object of vector class .

1 answer

  • answered 2017-06-17 19:28 GaurZilla

    Iterator itr=v.iterator();
    

    Here 'v' is collection class which is has a child class which implements iterator interface and iterator() method create instance of that child class and that is how iterator interface is being used.

        public Iterator<E> iterator() {
            return new Itr();
        }
    
    private class Itr implements Iterator<E>{
    //It has next() and hasNext() and other method implementation.
    }
    

    As per JAVA interface concepts, we can't instantiate an interface but its reference can point to the child object which will be provided by the collection class's child class in this case.