Iterator interface, use in ArrayList. Java

0

I understand that when an interface is implemented all the methods it contains must be implemented, since the methods declared in an interface are abstract and only the header is declared ... That's why I do not fully understand how the iterator () method belonging to the ArrayList class works. I know it returns an instance of the iterator interface, and we can use this instance without overwriting its methods > hasNext (), next (), remove () . Why can your methods be used if we have not overwritten them and therefore we have not given them an operation? An example:

Iterator <String> mi_iterador=lista.iterator();
 while(mi_iterador.hasNext()){
   System.out.println(mi_iterador.next());
 }

This code works perfectly, but I have never used the methods mentioned above.

    
asked by Javi 21.07.2018 в 22:17
source

1 answer

1

The ArrayList class implements the Iterable interface, when implemented it overwrites the iterator() method that returns an Iterator type object, but since it is also an interface and all its methods must be implemented, it is convenient to declare a class abstract, within the ArrayList class, that implements the Iterator interface and this would be the one that will implement all its methods and will be able to instantiate an object.

Summary in code:

public class ArrayList implements Iterable<E> ...{

       private Miclase implements Iterator<E>{

       private Miclase(){
       }
       @Override
       public boolean hasNext(){}
       public E next(){}
       public void remove(){}
       //etc etc

       }

       @Override
       public Iterator<E> iterator(){
       Iterator<E> iterator = new Miclase();
       return iterator;

      }
}

I hope I have resolved your doubt.

    
answered by 22.07.2018 / 07:24
source