📌  相关文章
📜  Java中的 AbstractList iterator() 方法及示例

📅  最后修改于: 2022-05-13 01:55:18.088000             🧑  作者: Mango

Java中的 AbstractList iterator() 方法及示例

Java.util.AbstractList类的iterator()方法用于以正确的顺序返回此列表中元素的迭代器。

此实现返回迭代器接口的直接实现,依赖于后备列表的 size()、get(int) 和 remove(int) 方法。

句法:

public Iterator iterator()

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

下面是说明iterator()方法的示例。

示例 1:

// Java program to demonstrate
// iterator() method
// for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // Creating object of AbstractList
            AbstractList
                arrlist1 = new ArrayList();
  
            // Populating arrlist1
            arrlist1.add(10);
            arrlist1.add(20);
            arrlist1.add(30);
            arrlist1.add(40);
            arrlist1.add(50);
  
            // print arrlist1
            System.out.println("ArrayList : "
                               + arrlist1);
  
            // creating object of Iterator
            // using iterator() method
            Iterator it = arrlist1.iterator();
  
            // printing the iterated value
            while (it.hasNext()) {
                System.out.println("Value is : "
                                   + it.next());
            }
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
ArrayList : [10, 20, 30, 40, 50]
Value is : 10
Value is : 20
Value is : 30
Value is : 40
Value is : 50

示例 2:

// Java program to demonstrate
// iterator() method
// for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // Creating object of AbstractList
            AbstractList
                arrlist1 = new ArrayList();
  
            // Populating arrlist1
            arrlist1.add("A");
            arrlist1.add("B");
            arrlist1.add("C");
            arrlist1.add("D");
            arrlist1.add("E");
  
            // print arrlist1
            System.out.println("ArrayList : "
                               + arrlist1);
  
            // creating object of Iterator
            // using iterator() method
            Iterator it = arrlist1.iterator();
  
            // printing the iterated value
            while (it.hasNext()) {
                System.out.println("Value is : "
                                   + it.next());
            }
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
ArrayList : [A, B, C, D, E]
Value is : A
Value is : B
Value is : C
Value is : D
Value is : E