当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ArrayList iterator()用法及代码示例


Java Collection Framework中ArrayList类的iterator()方法用于按适当顺序获取此列表中元素的迭代器。返回的迭代器是fail-fast。

用法:

 Iterator iterator()

参数:此方法不接受任何参数。


返回值:此方法以正确的顺序返回此列表中元素的迭代器

以下示例说明了ArrayList.iterator()方法:

示例1:

// Java code to illustrate iterator() 
  
import java.util.*; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
        // Create and populate the list 
        ArrayList<String> list 
            = new ArrayList<>(); 
  
        list.add("Geeks"); 
        list.add("for"); 
        list.add("Geeks"); 
        list.add("is"); 
        list.add("a"); 
        list.add("CS"); 
        list.add("Students"); 
        list.add("Portal"); 
  
        // Displaying the list 
        System.out.println("The list is: \n"
                           + list); 
  
        // Create an iterator for the list 
        // using iterator() method 
        Iterator<String> iter 
            = list.iterator(); 
  
        // Displaying the values after iterating 
        // through the list 
        System.out.println("\nThe iterator values"
                           + " of list are: "); 
        while (iter.hasNext()) { 
            System.out.print(iter.next() + " "); 
        } 
    } 
}
输出:
The list is: 
[Geeks, for, Geeks, is, a, CS, Students, Portal]

The iterator values of list are: 
Geeks for Geeks is a CS Students Portal

示例2:

// Java code to illustrate iterator() 
  
import java.util.*; 
  
public class GFG { 
  
    public static void main(String args[]) 
    { 
        // Creating an empty ArrayList 
        ArrayList<Integer> list 
            = new ArrayList<Integer>(); 
  
        // Use add() method to add 
        // elements into the list 
        list.add(10); 
        list.add(15); 
        list.add(30); 
        list.add(20); 
        list.add(5); 
  
        // Displaying the list 
        System.out.println("The list is: \n"
                           + list); 
  
        // Create an iterator for the list 
        // using iterator() method 
        Iterator<Integer> iter = list.iterator(); 
  
        // Displaying the values 
        // after iterating through the list 
        System.out.println("\nThe iterator values"
                           + " of list are: "); 
        while (iter.hasNext()) { 
            System.out.print(iter.next() + " "); 
        } 
    } 
}
输出:
The list is: 
[10, 15, 30, 20, 5]

The iterator values of list are: 
10 15 30 20 5


相关用法


注:本文由纯净天空筛选整理自29AjayKumar大神的英文原创作品 ArrayList iterator() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。