显示IDEA中所有快捷键 ctrl+j
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* @author admin
* @version 1.0.0
* @ClassName CollectionIterator.java
* @Description TODO
* @createTime 2021年09月10日 16:03:00
*/
public class CollectionIterator {
public static void main(String[] args) {
Collection<Object> col = new ArrayList<>();
col.add(new book("三国演义","张三",10.2));
col.add(new book("红楼","张四",12.2));
col.add(new book("六神演义","张五",5.2));
col.add("jackie");
System.out.println("col="+col);
//1.先得到col对应的迭代器
Iterator<Object> iterator = col.iterator();
//2.使用while循环遍历
//此处有快捷键生成while循环,itit
//显示所有快捷键 ctrl+j
while(iterator.hasNext()){
//返回下一个元素,类型是Object
Object o = iterator.next();
System.out.println(o);
}
//3.当退出循环后这时迭代器指向最后一个元素
//itretaor.next();//会抛出异常NOSuchElementException
//4.如果想再次遍历,重置
iterator=col.iterator();
System.out.println("第二次遍历");
while (iterator.hasNext()) {
Object next = iterator.next();
}
}
}
class book{
private String name;
private String author;
private double price;
public book() {
}
public book(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "book{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}