import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
//Collectios 是集合类的上层接口 试下接口的具体实现类有 List ArrayList 等
//Collections 是针对集合类的一个 帮助类 实现相对应的集合中的元素的相关操作
public class iterator {
public static void main(String[] args) {
Collection col=new ArrayList();
col.add(new Book("三国演义", "罗贯中", 10.1));
col.add(new Book("红楼梦", "曹雪芹", 5.1));
col.add(new Book("小李飞刀", "古龙 ", 5.6));
//只要是实现了Collection这个接口就会去实现相对应的 迭代器 然后就去实例化相对应的迭代器方法就好
Iterator iterator=col.iterator();
while(iterator.hasNext()){
//这里的Object是编译时对象 而 运行内部则是运行时对象
Object obj = iterator.next();
System.out.println(obj);
}
//当我们退出while循环的时候
// iterator.next();//由于迭代器的指向已经指向了最后一位 这时候 再取必然报错 这时候需要重置迭代器
//对迭代器进行重置
iterator = col.iterator();
System.out.println("重置迭代器 进行第二次遍历");
while(iterator.hasNext()){
Object obj=iterator.next();
System.out.println(obj);
}
}
}
class Book{
private String name;
private String author ;
private double price ;
public Book(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
public double getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
}
public void setAuthor(String author) {
this.author = author;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
使用迭代器对集合元素进行遍历
Colletions 是集合类的帮助接口
Collection 是集合类的接口。