Can somebody explain to me why is the method Iterator<E> iterator();
defined in java.util.Collection
? Collection already extends java.lang.Iterable
; this method is redundant. Is this for convenience?
The Java Iterable interface represents a collection of objects which is iterable - meaning which can be iterated. This means, that a class that implements the Java Iterable interface can have its elements iterated.
The Iterable interface was introduced in JDK 1.5. It belongs to java. lang package. In general, an object Implementing Iterable allows it to be iterated. An iterable interface allows an object to be the target of enhanced for loop(for-each loop).
The java.util.Collections class consists exclusively of static methods that operate on or return collections.Following are the important points about Collections − It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection.
The Collection
interface was introduced in Java 1.2 with the Collections API. The iterator
method was present then. However, the Iterable
interface wasn't introduced until Java 1.5. The reason that Collection
explicitly defines iterator
is because it predates Iterable
. The idea of a Collection
returning an Iterator
predates the idea of Iterable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With