java设计模式之迭代器

Jdk里最不缺得就是迭代器,自己写一个,加深下理解

public class CustomList<T> implements Iterable<T> {
    private final Object[] items = new Object[20];
    private int size = 0;

    public void add(T t) {
        items[size] = t;
        size++;
    }

    public T get(int index) {
        return (T) items[index];
    }

    public T remove(int index) {
        if (index > size - 1 || index < 0) {
            throw new ArrayIndexOutOfBoundsException("下标越界");
        }
        T r = (T) items[index];
        for (int i = index; i < size - 1; i++) {
            items[i] = items[i + 1];
        }
        items[--size] = null;
        return r;
    }

    /**
     * 正向迭代
     *
     * @return
     */
    public Iterator<T> iterator() {

        return new Iterator<T>() {
            int index = 0;

            @Override
            public boolean hasNext() {
                return index < size;
            }

            @Override
            public T next() {
                return (T) items[index++];
            }
        };
    }

    /**
     * 反向迭代
     *
     * @return
     */
    public Iterator<T> reverseIterator() {

        return new Iterator<T>() {
            int index = size - 1;

            @Override
            public boolean hasNext() {
                return index >= 0;
            }

            @Override
            public T next() {
                return (T) items[index--];
            }
        };
    }

    @Override
    public String toString() {
        return "CustomList{" +
                "items=" + Arrays.toString(items) +
                ", size=" + size +
                '}';
    }

    public static void main(String[] args) {
        CustomList<Integer> list = new CustomList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + ",");
        }

        System.out.println();

        Iterator<Integer> reverseIterator = list.reverseIterator();
        while (reverseIterator.hasNext()) {
            System.out.print(reverseIterator.next() + ",");
        }
        
    }
    
}

 

上一篇:统计西游记词频


下一篇:716 css flex布局:flex-flow,flex-direction,flex-wrap,justify-content,align-items,align-content,flex,ord