一直好奇Foreach的语法,想ArrayList和HashMap,为什么foreach就可以遍历呢,今天自己做了一个简单的实现。
- public class SimpleForeach<T> implements Iterable<T>, Iterator<T>{
- private T[] t;
- /**
- * 迭代的游标值,-1表示迭代未开始。
- */
- private int index = -1;
- private int size;
- public SimpleForeach(T[] t) {
- this.t = t;
- this.size = t.length;
- }
- @Override
- public Iterator<T> iterator() {
- return this;
- }
- /**
- * Foreach首先调用这个方法,判断迭代是否已经结束。
- */
- @Override
- public boolean hasNext() {
- boolean flag = index < size - 1;
- if (index == size -1) {
- index = -1;
- }
- return flag;
- }
- /**
- * Foreach游标移动以及获取迭代值的逻辑方法
- */
- @Override
- public T next() {
- if (index < size - 1) {
- index++;
- return t[index];
- }
- return null;
- }
- @Override
- public void remove() {
- for (int i = size - 1; i >= 0; i--) {
- if (t[i] != null) {
- t[i] = null;
- return;
- }
- }
- }
- }