zoukankan      html  css  js  c++  java
  • 用Iterator实现遍历集合

    使用Collection类的Iterator,可以方便的遍历Vector, ArrayList, LinkedList等集合元素,避免通过get()方法遍历时,针对每一种对象单独进行编码。

    示例:

     

    1. Collection coll = new Vector(); //LinkedList(); //ArrayList();  
    2. coll.add("Tody");  
    3. coll.add("is");  
    4. coll.add("Sunday.");  
    5.   
    6. // Output all elements by iterator  
    7. Iterator it = coll.iterator();  
    8. while(it.hasNext()) {  
    9.     System.out.print(it.next() + " ");  
    10. }  

    输出:

    Tody is Sunday.

     

    1.hasNext()函数的API解释

    boolean java.util.Iterator.hasNext()

     

    hasNext

    boolean hasNext()
    Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

     

    Returns:
    true if the iteration has more elements

    ---------------------------------------------------------

    2.next()函数的API解释

    Object java.util.Iterator.next()

     

    next

    E next()
    Returns the next element in the iteration.

     

    Returns:
    the next element in the iteration
    Throws:
    NoSuchElementException - if the iteration has no more elements

     

     

    1. Collection coll = new HashSet();  
    2. coll.add("Tody");  
    3. coll.add("is");  
    4. coll.add("Sunday.");  
    5.   
    6. // Output all elements by iterator  
    7. Iterator it = coll.iterator();  
    8. while(it.hasNext()) {  
    9.     System.out.print(it.next() + " ");  
    10. }  

    输出:

    is Sunday. Tody

     

    由上面两个例子看出,在List和Set对象中,Iterator的next()方法返回的值是不一样的。

    原因是List属于线性集合,元素是有序的,读取时是按照数组的形式,一个接一个的读取,存储也是按照add的顺序添加的。

    而Set属于非线性的,是无序的,所以读取的元素与添加的顺序不一定一致。

    对于HashSet,其实它返回的顺序是按Hashcode的顺序。

    如果迭代也有序,则可以用LinkedHashSet。

  • 相关阅读:
    [VB]用API打开浏览文件夹对话框,选择文件夹
    C# 16进制与字符串、字节数组之间的转换
    DIV未知高度的垂直居中代码
    Webbrowser控件判断网页加载完毕的简单方法
    一些控制鼠标的例子!
    Kernel device tree: simplebus
    Display Serial Interface (From WIKI)
    消费提示:常见 处理器/显卡 性能排名网站 汇总
    HDMI notes From HDMI wiki
    Linux graphics stack 理解
  • 原文地址:https://www.cnblogs.com/htys/p/3214467.html
Copyright © 2011-2022 走看看