方法概览:
hasNext(): 判断是否还存在下一个元素 next(): 指针下移 并返回移动后的位置的元素(可以理解为初始index = -1)
注意事项:
01.调用next()之前 需要先调用hasNext() 否则若无下一个元素 会抛出NoSuchElementException异常(可直接使用快捷短语 itit 生成迭代while循环) 02.退出while循环后 迭代器指向集合中最后一个元素 此时调用iterator.next()将抛出NoSuchElementException异常(若想重新进行迭代 可重置迭代器 即对迭代器重新调用iterator()方法)
测试代码:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/*
hasNext(): 判断是否还存在下一个元素
next(): 指针下移 并返回移动后的位置的元素(可以理解为初始index = -1)
注:调用next()之前 需要先调用hasNext() 否则若无下一个元素 会抛出NoSuchElementException异常
*/
public class CollectionIterator {
public static void main(String[] args) {
Books book1 = new Books("西游记", "吴承恩", 20);
Books book2 = new Books("红楼梦", "曹雪芹", 20);
Books book3 = new Books("水浒传", "施耐庵", 20);
//创建集合
Collection<Books> collection = new ArrayList<>();
collection.add(book1);
collection.add(book2);
collection.add(book3);
//创建迭代器
Iterator<Books> iterator = collection.iterator();
//创建迭代循环(快捷短语 itit)
while (iterator.hasNext()) {
Books next = iterator.next();
System.out.println("book = " + next.toString());
}
//退出while循环后 迭代器指向集合中最后一个元素 此时调用iterator.next()将抛出NoSuchElementException异常
//若想重新进行迭代 可重置迭代器
iterator = collection.iterator();
while (iterator.hasNext()) {
Books next = iterator.next();
System.out.println("book = " + next);
}
}
}
class Books{
String name;
String author;
double price;
public Books(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 "Books{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
运行结果:
增强for循环(快捷短语iter 或 集合对象.for):
for (Books books : collection) {
System.out.println(books);
}
注:在集合中,增强for循环底层调用的仍然是迭代器
注:增强for循环在数组中同样适用,底层采用的是普通的数组遍历(普通for循环)