版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/HughGilbert/article/details/72567769
文章代码来自:来源
含义
- Iterable接口:实现了Iterable接口的类表明了属于该类的对象能够使用
for each
进行迭代 - Iterator接口:用以实现迭代机制的接口
内部实现
- Iterable接口
public interface Iterable
{
Iterator<E> iterator();
}
- Iterator接口
public interface Iterator
{
E next();
boolean hasNext();
void remove();
}
举例说明
- 以下总共有两个类,一个Student,一个Students,通过Students实现了Iterator和Iterable接口
/*
Student 类
*/
public class Student{
private String name;
private String Id;
public Student(String name,String Id){
this.name = name;
this.Id = Id;
}
public String getName(){
return name;
}
public String getId(){
return Id;
}
@Override
public String toString(){
return "[" + this.getClass() + " : " + this.name + " , " + this.Id + "]";
}
}
/*
Students 类
*/
public class Students implements Iterable<Student>
{
private Student[] records;
public Students(int length){
records = new Student[length];
for(int index = 0; index < length; index++){
records[index] = new Student("学生" + index , index);
}
}
public Iterator<Student> iterator(){
return new StudentsIterator();
}
private class StudentsIterator implements Iterator<Student>{
private int index = 0;
public Student next()
{
return records[index++];
}
public boolean hasNext()
{
return (index < records.length);
}
public void remove()
{
//抛出不支持操作异常
throw new UnsupportedOperationException();
}
}
}
/*
main 函数
*/
public class Demo{
public static void main(String[] args)
{
Students students = new Students(5);
for(Student student : students)
{
System.out.println(student);
}
}
}
过程中产生的疑问
- 数组类型的变量只有length属性,那要如何获得该变量的元素个数,只能通过设置一个count计数器吗?相关链接
- 数组也是一个对象,例如
...
Object b = new int[5];
...