iterator constructor java

http‮w//:s‬ww.lautturi.com
iterator constructor java

In Java, the Iterator interface is an interface that defines methods for iterating through the elements of a collection. It is typically implemented by classes that represent collections, such as List and Set.

The Iterator interface does not have a public constructor, so you cannot create an instance of Iterator directly. Instead, you can obtain an Iterator for a collection by calling its iterator() method. For example:

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");

Iterator<String> iter = list.iterator();

In this example, the iterator() method of the ArrayList class returns an Iterator that allows you to iterate through the elements of the list.

You can then use the Iterator to access the elements of the collection one by one, using its next() and hasNext() methods. For example:

while (iter.hasNext()) {
    String element = iter.next();
    System.out.println(element);
}

This code prints the elements of the list to the console, one element per line.

For more information on the Iterator interface and other ways to iterate through collections in Java, you can refer to the Java documentation or other online resources.

Created Time:2017-11-01 22:29:54  Author:lautturi