我们有两种方法实现集合的遍历,第一种就是使用Iterator迭代器,第二种就是使用增强for循环,实际上增强for循环的底层逻辑还是使用iterator迭代器,使用断点debug一下即可。当我们使用terator迭代器的时候步骤如下:
(1)使用while(iterator.hasNext())判断是否遍历完毕
(2)使用iterator.next()实现遍历


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class test {
@SuppressWarnings({"all"})
public static void main(String[] args) {
Collection list = new ArrayList();
list.add(new Book("三国","罗贯中",22.0));
list.add(new Book("西游记","吴承恩",36.3));
Iterator iterator = list.iterator();//迭代器
//One
while (iterator.hasNext()) {
Object obj = iterator.next();
System.out.println(obj);
}
System.out.println("==============");
//Two
for(Object obj1: list){
System.out.println(obj1);
}
}
}
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 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 +
'}';
}
}
2449

被折叠的 条评论
为什么被折叠?



