Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a method iterator() on java.util.Collection

Why is there the method iterator() defined on the interface java.util.Collection when it already extends java.util.Iterable which has this very method defined.

I'm thinking some sort of backward compatability or an opportunity to write some JavaDoc on the method at the collection level.

Any other ideas?

like image 680
Dan Avatar asked Jan 18 '10 14:01

Dan


People also ask

What is iterator method in collection in Java?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java. util package.

What does iterator method do?

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. Before you can access a collection through an iterator, you must obtain one.

What is the difference between the remove () method of collection and iterator in Java?

As per Sun , "Iterator. remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."


1 Answers

Backwards compatibility. Iterable was not introducted until 1.5 with the for(Object o : iterable) construct. Previously, all collections had to provide a means to iterate them.

like image 176
Matt Avatar answered Oct 12 '22 12:10

Matt