Iterator and iterator in java

Here is my understanding of the value of using Iterableand Iteratorin version 1.8 of java.

1)

java.util.AbstractList Iterablebecause it implements

Iterator<T> iterator();which is a contract for any class Iterable.

2)

java.util.AbstractList implements

Iterator<T> iterator();by creating an internal instance level class,

private class Itr implements Iterator<E> { ... }

which implements methods hasNext, nextand remove.

private class ListItr extends Itr implements ListIterator<E>{..}is just an extra tool on top of an iterator to implement types List.

3)

Is this the only purpose of these two interfaces Iterableand Iteratorto allow any object to be iterable? Please let me know if there is any other purpose of these two interfaces?

+4
source share
3 answers

, . , Iterable , , Iterator, . , , , , Iterator "".

, , Java Collections, . , API CSV CsvFile Iterable<List<String>> Iterator<List<String>>, List of String, next().

- , " " , Iterable. , CsvFile API, - :

CsvFile csvFile = new CsvFile(pathToCsvFile);
for (List<String> record : csvFile) {
    doSomethingWithIt(record);
}

" " , , Iterator, .

P.S. , , , AutoCloseable CsvFile try-with-resources.

+3

java.util.Collection java.util.Iterable. Iterable , . - , , java.util.Iterator.

,

0

Iterable, Iterator<T> iterator();. , Iterable, .

If you see Iterator documentation , in the See Also section, you'll find Collection , ListIterator , Iterable . Collection and ListIterator are Iterable by default because they internally extend Iterable. Therefore, Iterable is used together with Iterator.

0
source

Source: https://habr.com/ru/post/1599218/


All Articles