Java简单迭代器例子

一直好奇Foreach的语法,想ArrayList和HashMap,为什么foreach就可以遍历呢,今天自己做了一个简单的实现。

 

Java代码 复制代码  收藏代码
  1. public class SimpleForeach<T> implements Iterable<T>, Iterator<T>{   
  2.        
  3.     private T[] t;   
  4.        
  5.     /**  
  6.      * 迭代的游标值,-1表示迭代未开始。  
  7.      */  
  8.     private int index = -1;   
  9.     private int size;   
  10.        
  11.     public SimpleForeach(T[] t) {   
  12.         this.t = t;   
  13.         this.size = t.length;   
  14.     }   
  15.   
  16.     @Override  
  17.     public Iterator<T> iterator() {   
  18.         return this;   
  19.     }   
  20.   
  21.     /**  
  22.      * Foreach首先调用这个方法,判断迭代是否已经结束。  
  23.      */  
  24.     @Override  
  25.     public boolean hasNext() {   
  26.         boolean flag =  index < size - 1;   
  27.         if (index == size -1) {   
  28.             index = -1;   
  29.         }   
  30.            
  31.         return flag;   
  32.     }   
  33.   
  34.     /**  
  35.      * Foreach游标移动以及获取迭代值的逻辑方法  
  36.      */  
  37.     @Override  
  38.     public T next() {   
  39.         if (index < size - 1) {   
  40.             index++;   
  41.             return t[index];   
  42.         }   
  43.            
  44.         return null;   
  45.     }   
  46.   
  47.     @Override  
  48.     public void remove() {   
  49.         for (int i = size - 1; i >= 0; i--) {   
  50.             if (t[i] != null) {   
  51.                 t[i] = null;   
  52.                 return;   
  53.             }   
  54.         }   
  55.     }   
  56.   
  57. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值