Iterator(迭代器)
Iterator介绍
1、Iterator对象称为迭代器,主要用于遍历 Collection 集合中的元素
2、所有实现了Collection 接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象,即可以返回一个迭代器
3、Iterator 仅用于遍历集合,其本身并不存放对象。
Iterator运行原理
Iterator接口的方法
while循环
package com.zhang;
import java.util.ArrayList;
import java.util.Iterator;
public class Iterator_ {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(new Book("三国演义", "罗贯中", 10.1));
arrayList.add(new Book("红楼梦", "曹雪芹", 132.1));
arrayList.add(new Book("小李飞刀", "古龙", 23.43));
System.out.println(arrayList);
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
// 此时迭代器的指针已经到了最后一个元素,如果再运行Iterator.next()将会报错
// iterator.next(); // NoSuchElementException
// 重置迭代器指针的方法为:
iterator = arrayList.iterator();
System.out.println("-------------- 重置指针后,继续遍历 -------------- ");
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next);
}
}
}
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 +
'}';
}
}
for循环增强
简述:
增强for循环,可以替代迭代器,
特点:增强for循环其实是简单的Iterator。本质上是一样的,只能用于遍历数组和集合
基本语法:
package com.zhang;
import java.util.ArrayList;
import java.util.Iterator;
public class Iterator_ {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(new Book("三国演义", "罗贯中", 10.1));
arrayList.add(new Book("红楼梦", "曹雪芹", 132.1));
arrayList.add(new Book("小李飞刀", "古龙", 23.43));
System.out.println(arrayList);
// for循环增强
for (Object o :
arrayList) {
System.out.println(o);
}
}
}
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 +
'}';
}
}