Зачем в Java 2 интерфейса: Iterable и Iterator?
По-моему они только вносят путаницу. Я так понял их роли: Iterable говорит что по объектам класса в принципе можно итерироваться, а Iterator задает сами методы для итерирования. Но по-моему все это отлично смотрелось бы в одном интерфейсе. Который и объявлял бы класс итерируемым и одновременно задавал бы методы для итерирования.
Отслеживать
задан 8 фев 2016 в 6:30
Александр Елизаров Александр Елизаров
2,788 2 2 золотых знака 18 18 серебряных знаков 36 36 бронзовых знаков
Иногда приходится решать задачи, требующие реализации своих итераторов и Iterable. Вот пример не совсем стандартной работы с коллекциями, здесь нужно обойти две коллекции в определённом порядке. Если бы это была одна сущность, всё было бы заметно сложнее, пришлось бы писать свой класс коллекции. Но благодаря разделению этих интерфейсов, мы можем гибко комбинировать. blog.shamanland.com/2016/03/composite-iterator-ru.html
8 мар 2016 в 14:32
3 ответа 3
Сортировка: Сброс на вариант по умолчанию
Можно было бы об этом задуматься, если предполагаемое соответствие Iterable и его Iterator было «один к одному». Но дело обстоит иначе: Iterable может в некий момент обходиться несколькими Iterator сразу (возможно, ещё и в разных thread’ах!). То есть, это интерфейсы, представляющие две разных сущности: коллекцию и обход коллекции.
Уже поэтому стоит их разделить, поскольку в противном случае для нескольких параллельных обходов коллекция должна быть всегда завёрнута в итератор и иметь два вида копирования (для итератора и для коллекции), а тут уже просматривается явное нарушение SRP (Single Responsibility Principle, принципа единственной обязанности).
Отслеживать
ответ дан 8 фев 2016 в 6:37
user181100 user181100
Один — тот кто ездит. Это Iterator
Другой — тот на ком ездят. Это Iterable
Первый не возможен без Второго. Второй возможен без первого, но бесполезен.
А на самом деле Iterable — всего лишь способ задать стандартный механизм извлечения итератора. Он не является таким уж важным в деле итерации. Он не нужен совсем.
Например у List есть ещё listIterator, к которому Iterable вообще никакого отношения не имеет. но тем не менее это настоящий итератор и даже упруженный дополнительными возможностями.
Отслеживать
ответ дан 8 июн 2017 в 0:20
6,308 1 1 золотой знак 12 12 серебряных знаков 18 18 бронзовых знаков
. все это отлично смотрелось бы в одном интерфейсе
Не смотрелось бы.
Iterator — это интерфейс. То есть мы можем вызвать метод какого-то класса, передать ему итератор и как бы сказать: «вот тебе некая последовательность, пробегись-ка по ней и сделай ряд действий».
Благодаря абстрактности итератор может быть вообще не привязан ни к какой коллекции, а самостоятельно генерировать значения на лету!
Причём эти действия, связанные с последовательным проходом по элементам, одинаковы для любого типа контейнера.
Но даже если считать, что любой итератор завязан на своём контейнере, то всё равно получается нехорошо. Итератор — это вспомогательная сущность, состояние которой надо хранить. Плюс, как правильно заметил @D-side, итератор даже уровне восприятия является отдельной сущностью.
Видеоуикенд #100. Изучаем паттерн Iterator и интерфейс Iterable, обеспечиваем безопасность Java-приложений, практикуем парное программирование и развенчиваем страхи джунов

Разработчик Сергей Архипов объясняет, что такое паттерн Iterator и интерфейс Iterable в языке Java. На конкретных примерах вы узнаете, для чего нужен Iterator и как его использовать. Также Сергей осветил вопрос удаления и вставки элементов в LinkedList за константное время. В описании под видео приложена ссылка на исходники кода, показанного в видеоролике.
Алексей Бабенко — +10 к безопасности кода на Java за 10 минут
Язык Java считается достаточно безопасным языком, поскольку JVM защищает исполняемый код от нарушения границ массива, его указатели имеют строгие ограничения на использование, а приведение типов и инициализация переменных грамотно организовано. Тем не менее, в Java существует ряд недостатков, которые могут привести к компрометации приложений. Алексей Бабенко подробно изложит, на что следует обратить особое внимание при разработке приложения, чтобы оно стало более защищенным от хакеров.
Парное программирование
Если вы еще не знакомы с парным программированием, то сегодня можете узнать все преимущества этой практики работы с кодом. Артем Димитров подробно расскажет, почему программирование с напарником может оказаться очень эффективным для решения определенных задач, в том числе при обучении.
Как попасть в IT и не сгореть от тревог, неудач и синдрома самозванца — Проблемы джунов
Ведущие подкаста “307 пакетов” подняли в своем видео острую для многих новичков в IT тему борьбы со страхами на рабочем месте. Во время полуторачасового разговора они разобрали, как преодолеть страх не пройти испытательный срок, как перестать сравнивать себя с другими программистами и многие другие злободневные для джуниоров вопросы.
Difference between Iterator and Iterable in Java
This post will discuss differences between the Iterator and Iterable in Java.
Both Iterator and Iterable are interfaces in Java that look very similar and are often confusing for beginners, but both are two different things. In short, if any class implements the Iterable interface, it gains the ability to iterate over an object of that class using an Iterator.
Now let’s discuss the major differences between the two in detail:
1. An Iterable represents a collection that can be traversed. Implementing the Iterable interface allows an object to make use of the for-each loop. It does that by internally calling the iterator() method on the object. For example, the following code only works as a List interface extends the Collection interface, and the Collection interface extends the Iterable interface.
List
for ( String person : persons ) <
System . out . println ( person ) ;
Please note that we can also call the forEach() method on an iterable starting from Java 8, which performs the given action for each element of the Iterable . It is worth noting that the default implementation of forEach() also uses for-each internally.
On the other hand, Iterator is an interface that allows us to iterate over some other object, which is a collection of some kind. To iterate over an Iterator , we can use hasNext() + next() methods in a while loop, as shown below:
Iterator
while ( iterator . hasNext ( ) ) <
System . out . println ( iterator . next ( ) ) ;
Starting from Java 8, we can also easily iterate over an Iterator by using the forEachRemaining() method.
Iterator
iterator . forEachRemaining ( System . out :: println ) ;
One can also use an Iterator inside a for-each loop by wrapping converting the Iterator into an Iterable by using a lambda:
for ( Integer i : ( Iterable
System . out . println ( i ) ;
2. Any class that implements the Iterable interface needs to override the iterator() method provided by the Iterable interface. The iterator() method returns an Iterator , which then can be used to iterate over an object of that class.
Any class implementing the Iterator interface needs to override the hasNext() and next() methods provided by the Iterator interface. The hasNext() method returns true if the iteration has more elements, and the next() method returns the next element in the iteration.
3. The Iterator instance stores the iteration state. That means it provides utility methods to get the current element, check if the next element exists, and move forward to the next element if present. In other words, an Iterator remembers the current position in a collection and returns the next item in sequence if present. The Iterable , on the other hand, doesn’t maintain any such iteration state.
4. The contract for Iterable is that it should produce a new instance of an Iterator every time the iterator() method is called. This is because the Iterator instance maintains the iteration state, and things won’t work as if the implementation returns the same Iterator twice.
5. For an Iterable , we can move forward only in the forward direction, but some of the Iterator subinterface like ListIterator allows us to move back and forth over a List .
Also, Iterable doesn’t provide any method to modify its elements, nor can we modify them using the for-each loop. But Iterator allows removing elements from the underlying collection during the iteration with the remove() method.
That’s all about the differences between Iterator and Iterable in Java.
What is the difference between iterator and iterable and how to use them?
I am new in Java and I’m really confused with iterator and iterable. Can anyone explain to me and give some examples?
23.5k 8 8 gold badges 96 96 silver badges 95 95 bronze badges
asked Jul 28, 2011 at 17:35
Charles Cai Charles Cai
2,741 4 4 gold badges 19 19 silver badges 10 10 bronze badges
Iterable
Sep 1, 2022 at 0:00
15 Answers 15
An Iterable is a simple representation of a series of elements that can be iterated over. It does not have any iteration state such as a «current element». Instead, it has one method that produces an Iterator .
An Iterator is the object with iteration state. It lets you check if it has more elements using hasNext() and move to the next element (if any) using next() .
Typically, an Iterable should be able to produce any number of valid Iterator s.
answered Jul 28, 2011 at 17:41
109k 30 30 gold badges 202 202 silver badges 202 202 bronze badges
will that matter if Iterable has interal or external iterator or it is possible to have any of them ?
Jul 2, 2015 at 7:20
An implementation of Iterable is one that provides an Iterator of itself:
public interface Iterable < Iteratoriterator(); >
An iterator is a simple way of allowing some to loop through a collection of data without assignment privileges (though with ability to remove).
public interface Iterator
answered Jul 28, 2011 at 17:43
Keith Pinson Keith Pinson
7,855 7 7 gold badges 61 61 silver badges 105 105 bronze badges
I will answer the question especially about ArrayList as an example in order to help you understand better..
- Iterable interface forces its subclasses to implement abstract method ‘iterator()’.
public interface Iterable < . abstract Iteratoriterator(); //Returns an 'Iterator'(not iterator) over elements of type T. . >
- Iterator interface forces its subclasses to implement abstract method ‘hasNext()’ and ‘next()’.
public interface Iterator < . abstract boolean hasNext(); //Returns true if the iteration has more elements. abstract E next(); //Returns the next element in the iteration. . >
- ArrayList implements List, List extends Collection and Collection extends Iterable.. That is, you could see the relationship like
. And Iterable, Collection and List just declare abstract method ‘iterator()’ and ArrayList alone implements it.
- I am going to show ArrayList source code with ‘iterator()’ method as follows for more detailed information.
‘iterator()’ method returns an object of class ‘Itr’ which implements ‘Iterator’.
public class ArrayList . implements List, . < . public Iteratoriterator() < return new Itr(); >private class Itr implements Iterator < . public boolean hasNext() < return cursor != size; >@SuppressWarnings("unchecked") public E next() < checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; > . > >
- Some other methods or classes will iterate elements of collections like ArrayList through making use of Iterator (Itr).
public static void main(String[] args) < Listlist = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("f"); Iterator iterator = list.iterator(); while (iterator.hasNext()) < String string = iterator.next(); System.out.println(string); >>
Now, is it clear? 🙂
2,182 18 18 silver badges 16 16 bronze badges
answered Dec 8, 2017 at 1:50
Jaemoon Hwang Jaemoon Hwang
692 1 1 gold badge 9 9 silver badges 12 12 bronze badges
I Understood this post, but what if I want to write a method whose return type is Iterable
Jun 14, 2020 at 15:35
I know this is an old question, but for anybody reading this who is stuck with the same question and who may be overwhelmed with all the terminology, here’s a good, simple analogy to help you understand this distinction between iterables and iterators:
Think of a public library. Old school. With paper books. Yes, that kind of library.
A shelf full of books would be like an iterable. You can see the long line of books in the shelf. You may not know how many, but you can see that it is a long collection of books.
The librarian would be like the iterator. He can point to a specific book at any moment in time. He can insert/remove/modify/read the book at that location where he’s pointing. He points, in sequence, to each book at a time every time you yell out «next!» to him. So, you normally would ask him: «has Next?», and he’ll say «yes», to which you say «next!» and he’ll point to the next book. He also knows when he’s reached the end of the shelf, so that when you ask: «has Next?» he’ll say «no».
I know it’s a bit silly, but I hope this helps.
answered Jul 1, 2020 at 16:23
381 3 3 silver badges 3 3 bronze badges
very good example.. So cant we say. shelf of books is the thing and to go over it we have librarian. without librarian bookshelf has no value as we cant iterate over them
Oct 27, 2020 at 12:45
If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.
answered Jul 28, 2011 at 17:39
48.2k 5 5 gold badges 125 125 silver badges 132 132 bronze badges
FYI a java.util.Collection always implements java.util.Iterable.
Feb 6, 2013 at 22:40
Is it not java.lang.Iterable ?
Aug 1, 2016 at 9:18
It’s java.lang.Iterable
Jan 28, 2018 at 4:10
Implementing Iterable interface allows an object to be the target of the «foreach» statement.
class SomeClass implements Iterable <> class Main < public void method() < SomeClass someClass = new SomeClass(); . for(String s : someClass) < //do something >> >
Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.
answered Jul 7, 2014 at 13:30
Nageswaran Nageswaran
7,575 14 14 gold badges 56 56 silver badges 75 75 bronze badges
If any class is implementing Iterable it should have a Iterator() method in it right. Correct me if I am wrong.
Feb 11, 2015 at 7:42
yes. It should have interface’s unimplemented method. In this case it is Iterator.
Apr 14, 2015 at 15:15
Thanks for an intelligent answer. I came here to double check my understanding of Iterable vs Iterator. You confirmed it. All the other answers talk about the structure, which I guess is fine, but doesn’t answer the question of WHY I’d use one over the other.
Nov 2, 2016 at 16:08
For me, this is the best answer.
Feb 8, 2017 at 23:19
I wanted to know what is the benefit of For each loop for String s: someClass. Since someClass is java class object and s String ref. Under what cirsumstances one should go with such sort of implementations.
Jul 16, 2019 at 18:27
The most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.
answered Aug 27, 2014 at 3:37
Praveen Kishor Praveen Kishor
2,473 1 1 gold badge 23 23 silver badges 28 28 bronze badges
I was wondering why collection classes do not implement Iterator interface directly (instead of implementing Iterable and returning Iterator object). This answer made it clear that — in that case it wouldn’t have been possible to traverse collection multiple times (and also simultaneously by multiple threads). This is very important answer.
Apr 23, 2019 at 15:36
As explained here, The “Iterable” was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.
Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
2,942 10 10 gold badges 34 34 silver badges 51 51 bronze badges
answered Nov 14, 2017 at 5:27
31 3 3 bronze badges
Consider an example having 10 apples. When it implements Iterable, it is like putting each apple in boxes from 1 to 10 and return an iterator which can be used to navigate.
By implementing iterator, we can get any apple, apple in next boxes etc.
So implementing iterable gives an iterator to navigate its elements although to navigate, iterator needs to be implemented.
9,712 146 146 gold badges 82 82 silver badges 122 122 bronze badges
answered Aug 17, 2017 at 6:08
Abhishek Malviya Abhishek Malviya
21 1 1 bronze badge
Question:Difference between Iterable and Iterator?
Ans:
iterable: It is related to forEach loop
iterator: Is is related to Collection
The target element of the forEach loop shouble be iterable.
We can use Iterator to get the object one by one from the Collection
Iterable present in java.ḷang package
Iterator present in java.util package
Contains only one method iterator()
Contains three method hasNext(), next(), remove()
Introduced in 1.5 version
Introduced in 1.2 version
answered Apr 28, 2017 at 20:02
11 1 1 bronze badge
Basically speaking, both of them are very closely related to each other.
Consider Iterator to be an interface which helps us in traversing through a collection with the help of some undefined methods like hasNext(), next() and remove()
On the flip side, Iterable is another interface, which, if implemented by a class forces the class to be Iterable and is a target for For-Each construct. It has only one method named iterator() which comes from Iterator interface itself.
When a collection is iterable, then it can be iterated using an iterator.
For understanding visit these:
answered Jun 7, 2017 at 15:11
418 4 4 silver badges 11 11 bronze badges
Iterable were introduced to use in for each loop in java
public interface Collection extends Iterable
Iterator is class that manages iteration over an Iterable . It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
996 1 1 gold badge 8 8 silver badges 29 29 bronze badges
answered Feb 6, 2019 at 17:35
Ranuj Mahajan Ranuj Mahajan
11 1 1 bronze badge
Welcome to SO, you could always take the tour here, so that your answer would be more helpful and clean. In our case the question is asking for an explanation regarding the two classes, but your answer is quite confusing instead of clearing things out. Also try to keep a ref, while posting snippets from known/valid/certified sources, to make your answer more concrete.
Feb 6, 2019 at 18:23
In addition to ColinD and Seeker answers.
In simple terms, Iterable and Iterator are both interfaces provided in Java’s Collection Framework.
Iterable
A class has to implement the Iterable interface if it wants to have a for-each loop to iterate over its collection. However, the for-each loop can only be used to cycle through the collection in the forward direction and you won’t be able to modify the elements in this collection. But, if all you want is to read the elements data, then it’s very simple and thanks to Java lambda expression it’s often one liner. For example:
iterableElements.forEach (x -> System.out.println(x) );
Iterator
This interface enables you to iterate over a collection, obtaining and removing its elements. Each of the collection classes provides a iterator() method that returns an iterator to the start of the collection. The advantage of this interface over iterable is that with this interface you can add, modify or remove elements in a collection. But, accessing elements needs a little more code than iterable. For example:
for (Iterator i = c.iterator(); i.hasNext(); ) < Element e = i.next(); //Get the element System.out.println(e); //access or modify the element >
Sources: