Week 51 — What is `Iterable` and how does it relate to for-each/enhanced `for` loops?
Question of the Week #51
What is
Iterable
and how does it relate to for-each/enhanced for
loops?8 Replies
Iterable
is an interface for objects that can be iterated over. It contains a single method named iterator
which should return an Iterator
object. This object allows to navigate through the Iterable
and access its elements. It has a hasNext
method which checks whether further elements are available and a next
method which gets the current element and moves to the next.
As an example, the following Range
record implements Iterable
to iterate over Integer
s starting from a specific element until a specific element with a given step size.
Once we have an
Iterable
object, an enhanced for loop can be used to iterate over it.
This is equivalent to the following code:
📖 Sample answer from dan1st
It is an interface, that allows you to call the forEach method on the collection of data you are making. Example would be an Inventory class that takes a collection of Products.
Submission from smokeintitan
it is an interface which Collection also implement and
this how forEach is implemented
Submission from kokoko2023
Doesn't it allow objects to be the target of enhanced for-each/enhanced loops.
Submission from PNJ3.0#1519
Iterable is the posibility of iterating variable like integer ,double which well achieved during loops like for each and enhanced for loops
Here is code snippet:
int[] goals={2,4,5,8,1,0};
for(int position:goals){
System.out.println(position);
}
//the end.
Submission from trailblazer_g
Iterable
is an interface implemented for types with the ability to iterate. When a class implements the Iterable
Interface they are now forced to abide by the contract by implementing the iterator
method. This method returns an iterator that can be used to iterate over the object based on the contract of the interface. After implementing the iterator method, an Object of that type can now be iterated over by a for-each loop. Other than allowing for the new syntax, the Iterable interface also gives access to two other default methods: the forEach
method, providing an even more concise solution when paired with method reference; the spliterator
, an iterator with splitting capability suitable for parallelism. ⭐ Submission from karter907