Iterator接口 Iterator模式是用于遍历集合类的标准访问方法。它可以把访问逻辑从不同类型的集合类中抽象出来,从而避免向客户端暴露集合的内部结构。 Iterator模式总是用同一种逻辑来遍历集合: for(Iterator it = c.iterater(); it.hasNext(); ) { ... } 奥秘在于客户端自身不维护遍历集合的"指针",所有的内部状态(如当前元素位置,是否有下一个元素)都由Iterator来维护,而这个Iterator由集合类通过工厂方法生成,因此,它知道如何遍历整个集合。 客户端从不直接和集合类打交道,它总是控制Iterator,向它发送"向前","向后","取当前元素"的命令,就可以间接遍历整个集合。 首先看看java.util.Iterator接口的定义: public interface Iterator { boolean hasNext(); Object next(); void remove(); } 依赖前两个方法就能完成遍历,典型的代码如下: for(Iterator it = c.iterator(); it.hasNext(); ) { Object o = it.next(); // 对o的操作... } 在JDK1.5中,还对上面的代码在语法上作了简化: // Type是具体的类型,如String。 for(Type t : c) { // 对t的操作... } 每一种集合类返回的Iterator具体类型可能不同,Array可能返回ArrayIterator,Set可能返回SetIterator,Tree可能返回TreeIterator,但是它们都实现了Iterator接口,因此,客户端不关心到底是哪种Iterator,它只需要获得这个Iterator接口即可,这就是面向对象的威力。 要确保遍历过程顺利完成,必须保证遍历过程中不更改集合的内容(Iterator的remove()方法除外),因此,确保遍历可靠的原则是只在一个线程中使用这个集合,或者在多线程中对遍历代码进行同步。 最后给个完整的示例: Collection c = new ArrayList(); c.add("abc"); c.add("xyz"); for(Iterator it = c.iterator(); it.hasNext(); ) { String s = (String)it.next(); System.out.println(s); } 如果你把第一行代码的ArrayList换成LinkedList或Vector,剩下的代码不用改动一行就能编译,而且功能不变,这就是针对抽象编程的原则:对具体类的依赖性最小。
private static Map map = new HashMap();
static {
map.put("bbb", "XXXX");
map.put("aaa", "XXXX");
map.put("cccc", "XXXX");
...................
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
.................
Set set = map.keySet();
Iterator it = set.iterator();
Date date=new Date();
while (it.hasNext()) {
Object key =it.next();
Object value = map.get(key);
//Interface Iterator 中的三个方法
//
}
|
|