JDK内置迭代器类似.主要用于遍历对象
interface MyIterator {
boolean isFirst();
boolean isLast();
void first();
Object next();
boolean hasNext();
}
class ConcreteMyAggregate {
private List<String> list = new ArrayList<>();
public void add(String str) {
this.list.add(str);
}
public void remove(String str) {
this.list.remove(str);
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public ConcreteIterator createIterator() {
return new ConcreteIterator();
}
private class ConcreteIterator implements MyIterator {
private int cursor;
@Override
public boolean isFirst() {
return cursor == 0;
}
@Override
public boolean isLast() {
return cursor == (list.size() - 1);
}
@Override
public void first() {
cursor = 0;
}
@Override
public Object next() {
String s = list.get(cursor);
cursor++;
return s;
}
@Override
public boolean hasNext() {
return cursor < (list.size());
}
}
}
/**
* 迭代器模式
*/
public class Iterator {
public static void main(String[] args) {
ConcreteMyAggregate aggregate = new ConcreteMyAggregate();
aggregate.add("1");
aggregate.add("2");
aggregate.add("3");
aggregate.add("4");
MyIterator iterator = aggregate.createIterator();
while (iterator.hasNext()) {
System.out.println(iterator.isFirst() + "-->" + iterator.isLast());
System.out.println(iterator.next());
}
Map<String, String> map = new HashMap<>();
map.put("1", "456");
map.put("2", "456");
map.put("3", "456");
Set<Map.Entry<String, String>> entries = map.entrySet();
java.util.Iterator<Map.Entry<String, String>> iterator1 = entries.iterator();
while (iterator1.hasNext()) {
Map.Entry<String, String> next = iterator1.next();
System.out.println(next.getKey() + "-->" + next.getValue());
}
}
}