The use of Iterator and Iterable interfaces

Why do you have to implement the Iterable interface? Why not just implement the Iterator interface directly?
Take a look at the collection classes in JDK, such as the List family or the Set family,
all inherit the Iterable interface, but do not directly inherit the Iterator interface.
It makes sense when you think about it. Because the core method next() or hasNext()
of the Iterator interface depends on the current iteration position of the iterator.
If Collection directly inherits the Iterator interface, it will inevitably cause the collection object to contain the data (pointer) of the current iteration position.
When collections are passed between methods, the result of the next() method can become unpredictable because the current iteration position cannot be preset.
Unless you add a reset() method to the Iterator interface to reset the current iteration position.
But even so, the Collection can only have one current iteration position at the same time.
Not so with Iterable, where each call returns an iterator counting from the beginning.
Multiple iterators do not interfere with each other.

Student.class

public class Student {

    private String id;
    private String name;

    public Student() {
        super();
    }
    public Student(String id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }

}

StuSet.class

public class StuSet implements Iterable<Student> {

    //存储Student对象的数组
    private Student[] students = new Student[10];
    //记录数组存储的最后一个Student对象的索引+1,也就是数组存储的Student对象的个数
    private int indexes = 0;

    public StuSet(){}

    //添加Student对象
    public void add(Student stu){
        //如果students数组存储的对象已经达到上限
        if(indexes==students.length){
            int length = students.length * 2;
            Student[] stus = new Student[length];
            //把students数组存储的所有对象拷贝到拥有它2倍索引的stus数组中去
            System.arraycopy(students, 0, stus, 0, this.students.length);
            students = stus;
            students[indexes] = stu;
        } else {
            students[indexes] = stu;
        }
        indexes++;  
    }

    //返回目前存了多少个Student对象
    public int size(){
        return indexes;
    }

    //返回Students数组总长度
    public int totalSize(){
        return students.length;
    }

    @Override
    public Iterator<Student> iterator() {
        return new StudentIterator();
    }

    //实现Iterator接口的私有内部类,外界无法直接访问
    private class StudentIterator implements Iterator<Student>{

        //当前迭代元素的下标
        private int index = 0;

        // 判断是否还有下一个元素,如果迭代到最后一个元素就返回false
        @Override
        public boolean hasNext() {
            return index != indexes;
        }

        @Override
        public Student next() {
            return students[index++];
        }

        // 这里不支持,抛出不支持操作异常
        public void remove(){
            throw new UnsupportedOperationException();
        }   
    }
}

Test.class

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StuSet stuSet = new StuSet();
        for(int i = 0; i < 16; i++){
            stuSet.add(new Student("123456","某人"));
        }
        System.out.println("目前数组存了: "+stuSet.size()+"个学生对象");
        System.out.println("目前数组的总长度是: "+stuSet.totalSize()+"个索引");
        for(Student s : stuSet){
            System.out.println(s.getId() + " "+s.getName());
        }
    }
}

console:

目前数组存了: 16个学生对象
目前数组的总长度是: 20个索引
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人
123456 某人

https://www.cnblogs.com/softidea/p/5167676.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326710241&siteId=291194637