Назначение
Дает возможность последовательно обойти все элементы составного объекта, не раскрывая его внутреннего представления.
??? концепции "внутреннего" и "внешнего" итератора.
Использование шаблона в JDK
(примеры частично взяты с этого ресурса)
----------------------------------------------------------------
----------------------java.util.Iterator----------------------
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class TestIterator {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
for (Integer i : list) {
System.out.print(i + " ");
}
System.out.println();
for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext();) {
System.out.print(iterator.next() + " ");
}
System.out.println();
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
Company company = new Company(Arrays.asList(
new Employee("Mike", 45),
new Employee("Sara", 21)));
for (Employee emp : company) {
System.out.println(emp);
}
}
}
class Company implements Iterable<Employee>{
private List<Employee> employees = new ArrayList<>();
Company(List<Employee> employees) {
this.employees = employees;
}
@Override
public Iterator<Employee> iterator() {
return new ArrayList<>(employees).iterator();
}
}
class Employee {
private String name;
private int age;
Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Employee[name=" + name + ", age=" + age +']';
}
}
----------------------------------------------------------------
---------------------
java.sql.ResultSet---------------------
public class PersonDao {
private static final String SQL
= "SELECT name, age FROM Persons";
public List<Person> allPersons() throws SQLException {
Connection conn = DriverManager.getConnection("...");
PreparedStatement stmt = conn.prepareStatement(SQL);
ResultSet rs = stmt.executeQuery();
ArrayList<Person> result = new ArrayList<>();
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
result.add(new Person(name, age));
}
return result;
}
}
public class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}