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?
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.
An implementation of Iterable
is one that provides an Iterator
of itself:
public interface Iterable<T>
{
Iterator<T> iterator();
}
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<E>
{
boolean hasNext();
E next();
void remove();
}
See Javadoc.
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 Iterator<T> iterator(); //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
'Iterable <- Collection <- List <- ArrayList'
. 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<E> ... implements List<E>, ... { ... public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { ... 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).
Here is a simple example.
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String string = iterator.next();
System.out.println(string);
}
}
Now, is it clear? :)
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.
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.
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.
Implementing Iterable interface allows an object to be the target of the "foreach" statement.
class SomeClass implements Iterable<String> {}
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.
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.
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.
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
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:
ITERABLE: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Iterable.java
ITERATOR http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Iterator.java
Iterable
were introduced to use in for each loop in java
public interface Collection<E> extends Iterable<E>
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.
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:
- Java Doc Iterable
- Java Doc Iterator
An anonymous class easily converts an Iterator
to an Iterable
and lets you use the Iterable
syntax (for loops, forEach()
).
Example: consider an Iterator<T> it
for (T element : new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return it;
}
}) {
//do something with `T element`
}
Abstracted in a function
static <T> Iterable<T> toIterable(Iterator<T> it) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return it;
}
};
}
Usage
for (T element: toIterable(it) {
...
}
Most java interfaces ends with 'able'. examples are Iterable, Cloneable, Serializable, Runnable, etc. Therefore, Iterable is an interface that has an abstract method called iterator() which returns an Iterator object.
public interface Iterable {
abstract Iterator<T> iterator();
}
Iterator interface has abstract method 'hasNext()' and 'next()'.
public interface Iterator {
abstract boolean hasNext();
abstract E next();
}
A clear use is a List which extends->Collections Interface->extends Iterable
List<String> countrylist = new ArrayList<>();
list.add("US");
list.add("China");
list.add("Japan");
list.add("India");
Iterator<String> it = countrylist.iterator();
while (it.hasNext()) {
String string = it.next();
System.out.println(string);
}
精彩评论