collection迭代器遍历
时间: 2023-08-24 19:15:13 浏览: 100
Collection的迭代器遍历有多种方式。一种方式是使用迭代器进行遍历。首先,我们需要通过调用集合的iterator()方法来获取迭代器对象。然后,我们可以使用while循环和迭代器的hasNext()和next()方法来遍历集合中的元素。具体代码如下所示:
```
Collection<String> c = new ArrayList<>();
c.add("语文书");
c.add("英语书");
c.add("数学书");
c.add("课外书");
Iterator<String> iterator = c.iterator();
while (iterator.hasNext()){
String s = iterator.next();
System.out.println(s);
}
```
另一种方式是使用增强for循环。我们可以直接使用增强for循环来遍历集合中的元素,无需显式地使用迭代器。具体代码如下所示:
```
Collection<String> c = new ArrayList<>();
c.add("语文书");
c.add("英语书");
c.add("数学书");
c.add("课外书");
for (String s : c) {
System.out.println(s);
}
```
这两种方式都可以用来遍历Collection集合中的元素,具体选择哪种方式取决于个人的喜好和需求。\[1\]\[2\]
#### 引用[.reference_title]
- *1* [Collection遍历方式](https://blog.csdn.net/qq_42108331/article/details/130624291)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [Java Collection集合的三种遍历方式](https://blog.csdn.net/m0_71485750/article/details/127340201)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Java中集合Collection遍历的三种方式](https://blog.csdn.net/m0_60438688/article/details/123603025)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文