• JAVA集合的遍历for循环、Iterator迭代器


    java中提供了很多个集合,它们在存储元素时,采用的存储方式不同。我们要取出这些集合中的元素,可通过一种通用的获取方式来完成。

    Collection集合元素的通用获取方式:在取元素之前先要判断集合中有没有元素,如果有,就把这个元素取出来,继续在判断,如果还有就再取出出来。一直把集合中的所有元素全部取出。这种取出方式专业术语称为迭代。

     Iterator迭代器有

                hasNext()方法:

    用来判断集合中是否有下一个元素可以迭代。如果返回true,说明可以迭代。

                Next()方法:

    用来返回迭代的下一个元素,并把指针向后移动一位。

             图解:

                                               

    Collection接口描述了一个抽象方法iterator方法,所有Collection子类都实现了这个方法,并且有自己的迭代形式。

    //1,创建集合对象。
    Collection<String> coll = new ArrayList<String>();
    coll.add("abc1");
    coll.add("abc2");
    coll.add("abc3");
    coll.add("abc4");
     
    //2.获取容器的迭代器对象。通过iterator方法。
    Iterator it = coll.iterator();
     
    //3,使用具体的迭代器对象获取集合中的元素。参阅迭代器的方法
    while(it.hasNext()){
        System.out.println(it.next());
    }
     
    /*
    迭代器for循环的形式的使用
    for (Iterator it = coll.iterator(); it.hasNext(); ) {
        System.out.println(it.next());
    }
    */

    注意:在进行集合元素取出时,如果集合中已经没有元素了,还继续使用迭代器的next方法,将会发生java.util.NoSuchElementException没有集合元素的错误。

         集合中存储其实都是对象的地址。 

      集合中可以存储基本数值吗?jdk1.5版本以后可以存储了。因为出现了基本类型包装类,它提供了自动装箱操作(基本类型à对象),这样,集合中的元素就是基本数值的包装类对象。 

      存储时提升了Object。取出时要使用元素的特有内容,必须向下转型。

    Collection<String> coll = new ArrayList<String>();

    coll.add("abc");

    coll.add("aabbcc");

    coll.add("cat");

    Iterator<String> it = coll.iterator();

    while (it.hasNext()) {

        String str = it.next();

    //当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型

        System.out.println(str.length());

    }

     

         增强for循环遍历集合。

    格式:

    for(元素的数据类型 变量 : Collection集合or数组){

    }

    练习一:遍历数组int[] arr = new int[]{11,22,33};
    
    for (int n : arr) {//变量n代表被遍历到的数组元素
        System.out.println(n);
    }
    练习二:遍历集合
    Collection<String> coll = new ArrayList<String>();
    coll.add("a1");
    coll.add("a2");
    coll.add("a3");
    coll.add("a4");
    for(String str : coll){//变量Str代表被遍历到的集合元素
        System.out.println(str);
    }

    增强for循环和老式的for循环有什么区别?

    注意:新for循环必须有被遍历的目标。目标只能是Collection或者是数组。

    建议:遍历数组时,如果仅为遍历,可以使用增强for如果要对数组的元素进行 操作,使用老式for循环可以通过角标操作。

  • 相关阅读:
    设置sqlplus输出格式
    Using CrunchBase API
    Docker ( Is docker really better than VM ?)
    Cross platform GUI for creating SSL certs with OpenSSL
    PHP, Python Nginx works together!
    Your personal Mail Server iRedMail on ubuntu14.04 x64
    iphone/ipad/iOS on Linux Debian7/ubuntu12.04/linuxmint13/ubuntu14.04 compiling from source
    Internet Liberity -- a specific anonymous internet guide
    Organic Solar Cells
    Organic Solar Cells
  • 原文地址:https://www.cnblogs.com/time-to-despair/p/9763095.html
Copyright © 2020-2023  润新知