Discuss / Java / 自己模仿的集合类

自己模仿的集合类

Topic source

package demo.collection;

import java.util.Iterator;

import java.util.List;

public class ReverseList<T> implements Iterable<T> {

    private List<T> list;

    public ReverseList(List<T> list) {

        this.list = list;

    }

    @Override

    public Iterator<T> iterator() {

        return new ReverseIterator(list.size());

    }

    class ReverseIterator implements Iterator {

        int index;

        public ReverseIterator(int index) {

            this.index = index - 1;

        }

        @Override

        public boolean hasNext() {

            return index >= 0;

        }

        @Override

        public T next() {

            return ReverseList.this.list.get(index--);

        }

    }

}

ReverseList<Integer> integers = new ReverseList<>(Arrays.asList(1,2,3,4,5,6,7));

for(Integer i: integers) {

    System.out.print(i);

    System.out.print("  ");

}

System.out.println();

/**

7  6  5  4  3  2  1  

*/


  • 1

Reply