Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method iterator() declared in java.util.Collection and in java.lang.Iterable, its superinterface?

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?

like image 754
Ilya K. Avatar asked Nov 13 '15 16:11

Ilya K.


People also ask

What is iterable in Java collection?

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.

What is iterable in Java with example?

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).

What is Java Util Collection?

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.


1 Answers

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.

like image 82
rgettman Avatar answered Oct 04 '22 04:10

rgettman