JAVA集合——Iterator遍历

package com.it.java;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import org.junit.Test;

public class TestIterator {
    //面试题:
    @Test
    public void testFor3() { //输出:0,1,2
        String[] str = new String[] {"AA","BB","DD"};
        for (String s : str) {
            s = "MM";//此处的S是新定义的局部变量,其值得修改不会对str本身造成影响
        }
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
    }

    @Test
    public void testFor2() { //输出:0,1,2
        String[] str = new String[] {"AA","BB","DD"};
        for (int i = 0; i < str.length; i++) {
            str[i] = i +"";
        }
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
    }


    /***********************************************/
    //使用增强for循环实现数组的遍历
    @Test
    public void testFor1() {
        String[] str = new String[] {"AA","BB","DD"};
        for(String s:str) {
            System.out.println(s);
        }
    }

    //使用增强for循环实现集合的遍历
    @Test
    public void testFor() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add("aa");
        coll.add(new Date());
        coll.add("BB");
        coll.add(new Person("MM",23));

        for(Object i:coll) {
            System.out.println(i);
        }
    }

    //错误写法
    @Test
    public void test2() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add("aa");
        coll.add(new Date());
        coll.add("BB");
        coll.add(new Person("MM",23));

        Iterator i = coll.iterator();
        while((i.next()) != null) {
            //报错:java.util.NoSuchElementException
            System.out.println(i.next());
        }
    }

    //正确写法:使用迭代器Iterator实现集合的遍历
    @Test
    public void test1() {
    Collection coll = new ArrayList();
    coll.add(123);
    coll.add("aa");
    coll.add(new Date());
    coll.add("BB");
    coll.add(new Person("MM",23));

    Iterator i = coll.iterator();
    while(i.hasNext()) {
        System.out.println(i.next());
    }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值