How is the usage of iterator in Java?

In Java, Iterator is an interface used to iterate through elements in a collection. It provides a uniform way to access elements in the collection without needing to understand the internal structure of the collection.

The steps for using an Iterator are as follows:

  1. Call the iterator() method on the collection to retrieve an Iterator object.
  2. Use the hasNext() method to check if there is another element.
  3. Retrieve the next element using the next() method.
  4. Remove elements from the collection using the remove() method (optional operation).

Here is a simple example demonstrating how to use an Iterator to iterate over a List collection.

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    System.out.println(element);
}

In the example above, we first obtain an Iterator object by calling the iterator() method of ArrayList. We then use a while loop and the hasNext() method to iterate through the elements in the collection, and finally use the next() method to retrieve and print each element.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds