1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@SuppressWarnings("all")

// hasNext: 判断是否有下一个元素
// next: 指针后移并返回当前元素
// remove: 删除指针当前指向的元素

public class CollectionIterator {
public static void main(String[] args) {
List col = new ArrayList();
col.add(new Book("西游记","吴承恩",44.6));
col.add(new Book("红楼梦","曹雪芹",38.9));
col.add(new Book("水浒传","罗贯中",66.6));
System.out.println(col);
/* 遍历这个列表 */
// 1. 先得到col对应的迭代器
Iterator it = col.iterator();
// 2. 使用while循环遍历即可,快捷键itit
while(it.hasNext()){
Object obj = it.next(); // 返回的是Object对象
System.out.println(obj);
}
// 3. 当退出while循环后,这时迭代器it指向最后的元素
// it.next(); //报错 NoSuchElementException
// 4. 想再次遍历,需要重置迭代器
it = col.iterator();
}
}

class Book {
String name;
String author;
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 +
'}';
}
}