Java/Iterators

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
How to Setup Java on your PC
Java Data Types, Variables,and Arrays
Java Operators
Java Packages, Classes, and Interfaces
Java Program
Java Modifiers
Java Control Statements
Java Exception Handling
Java Object Oriented Programming
Java Wrappers
Java Strings
Java Math
Java Arrays
Java Random Numbers
Java Date and Time
Java Regular Expressions
Java Collections
* Java List
* Java Set
* Java Comparators
* Java Iterators
* Java Map
* Java Legacy Classes and Interfaces
Java Generics
Java Thread and Multithreading
Java IO and file Handling
Java Network Programming
Java RMI
Java Image, Audio, Video
Java GUI
Java Applets
Java Internationalization
JDBC
Java and XML

[edit] Java Iterators

Iterator is of great help when we want any operation to be executed in Cycles, so Iterator will be the best choice if we want the elements of a collection to cycle and display each element. Listiterator extends Iterator.

The following steps are recommended to be followed if we want to implement Iterator :


1. Call the collection’s Iterator ( ) method to get to the strat of the Iterator. 2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. 3. Within the loop, obtain each element by calling next( ).

We can also implement ListIterator for the collections that element that implement List interface and it works more or less like Iterator.

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
 
 
public class IteratorExample {
 
	public static void main(String args[]) {
		Set set = new LinkedHashSet();
		set.add("1");
		set.add("2");
		set.add("3");
		set.add("4");
 
		Iterator iter = set.iterator();
 
		for(;iter.hasNext();) {
			String element = (String) iter.next();
			System.out.println(element);
		}
	}
}