package com.collection_;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/*
1. Iterator 对象称为迭代器,主要用于遍历Collection集合中的元素
2. 所有实现了Collection接口的集合类都有一个iteration()方法,用以
返回一个Iterator接口的对象,即可以返回一个迭代器
3. Iterator仅用于遍历集合,Iterator本身并不存在对象
*/
public class CollectionIterator {
@SuppressWarnings({"all"})
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("红楼梦","曹雪芹",34.6));
//System.out.println("col=" + col);
//遍历 col 集合
//1. 先得到 col 对应的迭代器
Iterator iterator = col.iterator();
//2. 使用while循环遍历
// while (iterator.hasNext()) {//判断是否还有下一个数据
// //返回下一个元素,类型是Object
// Object obj = iterator.next();//用next()方法获取数据
// System.out.println("obj=" + obj);
// }
//快捷键,快速生成 itit
//显示所有快捷键的快捷键 ctrl + j
while (iterator.hasNext()) {
Object obj = iterator.next();
System.out.println("obj=" + obj);
}
//3. 当退出while循环后,只是iterator迭代器,指向了最后一个数据
//iterator.next();//NoSuchElementException异常
//4. 如果希望再次遍历,需要重置iterator
iterator = col.iterator();
System.out.println("======第二次遍历=========");
while (iterator.hasNext()) {
Object obj = iterator.next();
System.out.println("obj=" + 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 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 +
'}';
}
}
Collection遍历集合Iterator迭代器
最新推荐文章于 2023-04-03 19:43:48 发布