集合的遍历之Collection

集合的遍历之Collection

 

迭代器iterator接口

/**
* 集合元素的遍历操作,使用迭代器iterator接口
* 1.内部的方法 hasNext() 和 next() 搭配使用
* 2.集合对象每次调用iterator()都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前
*
* @author ccchai
* @create 2022-02-23 10:09
*/
public class IteratorTest {

   @Test
   public void test1(){
       Collection coll = new ArrayList();
       coll.add(123);
       coll.add(456);
       coll.add(false);
       coll.add(new String("hello"));
       coll.add(new Person("Mike",24));

       Iterator iterator = coll.iterator();

       //方式一:不推荐
//       for (int i = 0; i < coll.size(); i++) {
//           System.out.println(iterator.next());
//       }

       //方式二:推荐
       //hasNext():判断是否有下一个元素
       while (iterator.hasNext()){
           //next():①指针下移②将下移以后集合位置上的元素返回
           System.out.println(iterator.next());
      }
  }

   /*
   测试迭代器中的remove()
   如果还未调用next()或在上一次调用next()之后已经调用了remove(),再调用remove()都会报IllegalStateException
    */
   @Test
   public void test2(){
       Collection coll = new ArrayList();
       coll.add(123);
       coll.add(456);
       coll.add(false);
       coll.add(new String("hello"));
       coll.add(new Person("Mike",24));

       Iterator iterator = coll.iterator();

       while(iterator.hasNext()){
           Object next = iterator.next();
           //删除集合中的"hello"
           if ("hello".equals(next)){
               iterator.remove();
          }

      }
       iterator = coll.iterator();
       while (iterator.hasNext()){
           System.out.println(iterator.next());
      }
  }
}

 

foreach

/**
*
* jdk5.0 新增了foreach循环,用于遍历集合、数组
* @author ccchai
* @create 2022-02-23 10:51
*/
public class ForTest {
   @Test
   public void test1(){
       Collection coll = new ArrayList();
       coll.add(123);
       coll.add(456);
       coll.add(false);
       coll.add(new String("hello"));
       coll.add(new Person("Mike",24));

       //for(集合元素的类型 局部变量 : 集合对象)
       //内部仍然调用了迭代器
       for (Object obj : coll){
           System.out.println(obj);
      }
  }


   @Test
   public void test2(){
       int[] arr = new int[]{1,2,3,4,5};
       //for(数组元素的类型 局部变量 : 数组对象)
       for (int i : arr){
           System.out.println(i);
      }
  }

   @Test
   public void test3(){
       String[] arr = new String[]{"AA","AA","AA"};
       //方式一:普通for循环
//       for (int i = 0; i < arr.length; i++) {
//           arr[i] = "BB";
//       }

       //方式二:增强for循环
       for (String s : arr){
           s="BB";
      }

       for (int i = 0; i < arr.length; i++) {
           System.out.println(arr[i]);
      }
  }
}
posted @ 2022-02-23 11:04  阳光真好的博客  阅读(55)  评论(0)    收藏  举报