Introduction
The Iterable
interface in Java represents a collection of objects that can be iterated over. It is used as a foundation for collections to allow for enhanced for-loops and iteration.
Table of Contents
- What is
Iterable
? - Implementing
Iterable
- Common Methods
- Examples of
Iterable
- Conclusion
1. What is Iterable?
Iterable
is an interface that allows objects to be the target of the "for-each loop." It provides a standard way to iterate over a collection of elements.
2. Implementing Iterable
To implement Iterable
, a class must:
- Implement the
Iterable<T>
interface. - Override the
iterator()
method to return anIterator<T>
.
3. Common Methods
iterator()
: Returns an iterator over elements of typeT
.
4. Examples of Iterable
Example: Implementing Iterable
in a Custom Class
This example demonstrates how to implement the Iterable
interface in a custom class.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyCollection implements Iterable<Integer> {
private Integer[] items;
private int size;
public MyCollection(Integer[] items) {
this.items = items;
this.size = items.length;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < size;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return items[index++];
}
};
}
public static void main(String[] args) {
Integer[] data = {1, 2, 3, 4, 5};
MyCollection collection = new MyCollection(data);
for (Integer item : collection) {
System.out.println(item);
}
}
}
Output:
1
2
3
4
5
5. Conclusion
The Iterable
interface in Java is a fundamental part of the collections framework, allowing objects to be iterated over easily. By implementing Iterable
, you can create custom collections that can be used in enhanced for-loops, improving code readability and functionality.
Comments
Post a Comment
Leave Comment