Java自定义可迭代类

package com.company;

import java.util.Iterator;

public class ClassRoom implements Iterable<String> {

    private String[] students;

    public String[] getStudents() {
        return students;
    }

    public ClassRoom(String... students) {
        this.students = students;
    }

    @Override
    public Iterator<String> iterator() {
        return new ClassRoomIterator();
    }

    private class ClassRoomIterator implements Iterator<String> {
        private int cursor;

        @Override
        public boolean hasNext() {
            return cursor < students.length;
        }

        @Override
        public String next() {
            return students[cursor++];
        }
    }
}
package com.company;

import java.util.Iterator;

public class Main {

    public static void main(String[] args) {
        ClassRoom room = new ClassRoom("Jack", "rose");

        for (String string : room) {
            System.out.println(string);
        }

//        Iterator<String> iterator = room.iterator();
//        while (iterator.hasNext()){
//            System.out.println(iterator.next());
//        }
    }
}
posted @ 2020-04-17 22:17  xl4ng  阅读(364)  评论(0编辑  收藏  举报