设计模式-迭代器模式-代码展示

23种设计模式汇总讲解文档
汇总学习网址:Java23种设计模式-学习汇总

迭代器模式
基本已经用的很少了,java中我们常用List,Map已经实现了迭代器、一般是itrator()方法。
定义1 :提供一个方法访问一个容器对象中各个元素,而又不需要暴露该对象实现的具体细节

// java已经实现的迭代器的用法
List<String> list = new ArrayList<String>();
for(String str:list){
    
    
}

迭代器定义 Iterator<E>

public interface Iterator<E> {
    
    
    /**
     * @return {@code true} if the iteration has more elements
     * 返回是否还有下一个
     */
    boolean hasNext();

    /**
     * @return the next element in the iteration
     * 返回下一个属性
     */
    E next();

    /**
     * 移除方法,需要重写
     */
    default void remove() {
    
    
        throw new UnsupportedOperationException("remove");
    }

    /**
     * 具体解释请看下面链接
     */
    default void forEachRemaining(Consumer<? super E> action) {
    
    
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

forEachRemaining() : forEach()方法与forEachRemaining()方法的区别

迭代器:手写HashMap部分核心代码 Line:364-461

......
class Citerator implements Iterator<Entry< K, V >>{
    
    

      private int hashIndex = -1;
      private Node<K,V> next = null,local = null;
      public Citerator(){
    
    
         hashIndex = -1;
         getNext();
      }
      private Node<K,V> getNext(){
    
    
         if(!That.isEmpty()) {
    
    
            int len = table.length;
            // 说明进行的是初始化
            if(hashIndex < 0) {
    
    
               hashIndex = 0;
            }
            if(next == null|| next.next == null) {
    
    
               if(next!=null && next.next == null) {
    
    
                  hashIndex++;
               }
               for(int i=hashIndex;i<len;i++) {
    
    
                  if(table[i]!=null) {
    
    
                     next = table[i];
                     hashIndex = i;
                     return next;
                  }
               }
               // 运行到这里,证明没有下一个了
               next = null;
            }
            else {
    
    
               next = next.next;
               return next;
            }
         }
         return null;
      }
      @Override
      public boolean hasNext()
      {
    
    
         return next!=null;
      }

      @Override
      public Entry< K, V > next()
      {
    
    
         // 当前节点是什么不重要,获取下个节点,返回的节点就成为当前节点了。
         local = next;
         getNext();
         return local;
      }

      @Override
      public void remove()
      {
    
    
         That.remove(local.key);
      }
      
   }
......

运行的结果


  1. 《设计模式之禅》秦小波 ↩︎

猜你喜欢

转载自blog.csdn.net/u011008832/article/details/113873375