Java Tutorials
Java Methods
Java Classes
Java File Handling
Iterator
is something that can be used to connect to collections, such as ArrayList and HashSet. It is called "iterator" because "iterating" is a technical term for unlocking.
To use Iterator, you must import it into a java.util
package.
The iterator()
method can be used to get an Iterator
for any collection:
// Import the ArrayList class and the Iterator class
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
// Get the iterator
Iterator<String> it = cars.iterator();
// Print the first item
System.out.println(it.next());
}
}
To navigate the collection, use the hasNext()
and the following Iterator
modes:
while(it.hasNext()) {
System.out.println(it.next());
}
Iterators are designed to easily change the collections you enter. The remove()
method can remove items from the collection while looping.
Use an iterator to remove numbers less than 10 from a collection:
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);
Iterator<Integer> it = numbers.iterator();
while(it.hasNext()) {
Integer i = it.next();
if(i < 10) {
it.remove();
}
}
System.out.println(numbers);
}
}
Note: Trying to delete items using each for loop
or a for-each
loop will not work properly because the cluster changes size at the same time as the code tries to loop.