Java集合(二)--- 集合元素的遍历操作Iterator以及foreach
文章目录
- 一、使用迭代器Iterator接口
- 1.说明
- 2.代码
- 二、foreach循环,用于遍历集合、数组
提示:以下是本篇文章正文内容,下面案例可供参考
一、使用迭代器Iterator接口
1.说明
1.内部的方法: hasNext() 和 next()
2.集合对象每次调iterator()方法都得到一个全新的迭代器对象
3.默认游标都在集合的第一个元素之前。
4.内部定义了remove(),可以在遍历的时候,删除集合中的元素。此方法不同于集合直接调用remove()
2.代码
package com.tyust.edu;import org.junit.Test;import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;/*** 集合元素的遍历操作,使用Iterator接口* 内部的方法 hasNext()和next()* @author YML TYUST-XDU 2019-2026* @create 2023-10-09 15:54*/
public class IteratorTest {@Testpublic void test1(){Collection coll = new ArrayList();coll.add(123); //自动装箱coll.add(456);coll.add(new Person("Jerry", 20));coll.add(new String("Mary"));coll.add(false);Iterator iterator = coll.iterator();System.out.println(iterator.next());System.out.println(iterator.next());System.out.println(iterator.next());System.out.println(iterator.next());
// System.out.println(iterator.next());//报异常:NoSuchElementException
// System.out.println(iterator.next());//方式二:
// for (int i = 0; i < coll.size(); i++) {
// System.out.println(iterator.next());
// }//方式三:while(iterator.hasNext()){System.out.println(iterator.next());}}}
二、foreach循环,用于遍历集合、数组
代码如下(示例):
package com.tyust.edu;import org.junit.Test;import java.util.ArrayList;
import java.util.Collection;/*** jdk5.0 新增了foreach循环,用于遍历集合、数组* @author YML TYUST-XDU 2019-2026* @create 2023-10-09 16:51*/
public class ForTest {@Testpublic void test1() {Collection coll = new ArrayList();coll.add(123); //自动装箱coll.add(456);coll.add(new Person("Jerry", 20));coll.add(new String("Mary"));coll.add(false);//for(集合元素的类型 局部变量:集合对象)//内部仍然调用了迭代器for(Object obj:coll){System.out.println(obj);}}@Testpublic void test2(){int [] arr = new int[]{1,2,3,4,5,6};//for(数组元素的类型 局部变量:数组对象)for(int i:arr){System.out.println(i);}}@Testpublic void test3(){String []arr = new String[]{"MM","MM","MM"};for (int i = 0; i < arr.length; i++) {arr[i] = "GG";}for(String s:arr){s="GG";}for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}}}