📜  Java中的迭代器接口

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

Java中的迭代器接口

Java集合的Java迭代器接口允许我们访问集合的元素,并用于迭代集合中的元素(Map、List 或 Set)。它有助于轻松检索集合的元素并对每个元素执行操作。迭代器 是一个通用迭代器,因为它可以应用于任何 Collection 对象。我们只能使用迭代器在前向遍历。使用继承 Iterator 的ListIterator ,可以双向遍历。读取和删除操作都可以由迭代器接口执行。这包含在Java JDK 1.2 中。唯一的 Enumeration 是 JDK 1.0 中包含的第一个迭代器。要使用迭代器,我们必须导入Java.util 包。

枚举接口的限制:

在Java集合中使用 Iterator 接口代替 Enumeration。

  • 枚举是 不是通用迭代器,仅用于 Vector、Hashtable 等遗留类。
  • 迭代器允许调用者在迭代元素期间从给定集合中删除元素。
  • Enumeration中只能进行正向迭代。

迭代器接口的声明

public interface Iterator

E – 此迭代器返回的元素类型

迭代器的子接口

事件迭代器:

public interface EventIterator extends Iterator

EventIterators 是不可修改的。

方法: nextEvent() 返回 EventSet 中的下一个 Event。

列表迭代器

public interface ListIterator extends Iterator

列表的迭代器,它允许向前或向后遍历列表或在迭代期间修改列表并获取迭代器的当前位置。 ListIterator没有当前元素。

PrimitiveIterator, PrimitiveIterator.OfInt, PrimitiveIterator.OfLong

实现类:

  • BeanContextSupport.BCIterator
  • 事件读取器委托
  • 扫描器

示例:迭代器的实现

Collection Framework 中的所有类都提供 iterator() 方法,该方法返回 Iterator 的实例以迭代该集合中的元素。

Java
// Java program to show the usage of Iterator()
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class JavaIteratorExample1 {
    public static void main(String[] args)
    {
          // create a list
        List list = new LinkedList<>();
        list.add("Welcome");
        list.add("to");
        list.add("GFG");
  
        System.out.println("The list is given as : "
                           + list);
            
          // get the iterator on the list
        Iterator itr = list.iterator();
  
        // Returns true if there are more number of
        // elements.
        while (itr.hasNext()) {
            // Returns the next element.
            System.out.println(itr.next());
        }
  
        // Removes the last element.
        itr.remove();
        System.out.println(
            "After the remove() method is called : "
            + list);
    }
}


Java
// Java program to iterate over an arraylist
// using Iterator
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // initializing ArrayList
        List numbers
            = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80);
  
        // Looping ArrayList using Iterator
        Iterator it = numbers.iterator();
        while (it.hasNext())
            System.out.print(it.next() + " ");
    }
}


Java
// java program to show the creation of
// custom class that implements iterable interface
import java.util.*;
import java.io.*;
class Employees implements Iterable {
  
    List str = null;
    public Employees()
    {
        str = new ArrayList();
        str.add("practice");
        str.add("geeks");
        str.add("for");
        str.add("geeks");
        str.add("to");
        str.add("learn");
        str.add("coding");
    }
  
    // if we are implementing Iterable interface, the we
    // need to define the iterator() method of Iterable
    // interface
    @Override public Iterator iterator()
    {
        return str.iterator();
    }
}
  
public class EmployeesTester {
    public static void main(String[] args)
    {
        Employees emps = new Employees();
        for (String st : emps.str) {
            System.out.println(st);
        }
    }
}


Java
// java program to remove()
// elements from a collection
  
import java.util.ArrayList;
import java.util.Iterator;
  
public class MyClass {
    public static void main(String[] args)
    {
          // create a list of Integers
        ArrayList numbers
            = new ArrayList();
        numbers.add(12);
        numbers.add(8);
        numbers.add(2);
        numbers.add(23);
            
          // get the iterator on the list
        Iterator it = numbers.iterator();
        while (it.hasNext()) {
                
              // gives the next element
              // and iterator moves to next 
              // element
            Integer i = it.next();
  
            if (i < 10) {
                    
                  // removes the current element
                it.remove(); 
            }
        }
        System.out.println(numbers);
    }
}


Java
// Java program to show the usage of
// Iterator forEachRemaining()
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        //  initializing ArrayList
        List numbers
            = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80);
  
        numbers.iterator().forEachRemaining(
            System.out::println);
    }
}


输出
The list is given as : [Welcome, to, GFG]
Welcome
to
GFG
After the remove() method is called : [Welcome, to]

ArrayList 迭代器示例

Java

// Java program to iterate over an arraylist
// using Iterator
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // initializing ArrayList
        List numbers
            = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80);
  
        // Looping ArrayList using Iterator
        Iterator it = numbers.iterator();
        while (it.hasNext())
            System.out.print(it.next() + " ");
    }
}
输出
10 20 30 40 50 60 70 80 

开发自定义类迭代器

要为用户定义的 /custom 类提供类似的功能,我们应该按照以下步骤操作:

  • 定义自定义类。
  • 为这个自定义类定义集合类。
  • 集合类应导入Java.util 包并实现可迭代接口。
  • 这个集合类现在应该为 Iterable 接口的方法 iterator() 提供实现。

开发自定义类的示例代码:

Java

// java program to show the creation of
// custom class that implements iterable interface
import java.util.*;
import java.io.*;
class Employees implements Iterable {
  
    List str = null;
    public Employees()
    {
        str = new ArrayList();
        str.add("practice");
        str.add("geeks");
        str.add("for");
        str.add("geeks");
        str.add("to");
        str.add("learn");
        str.add("coding");
    }
  
    // if we are implementing Iterable interface, the we
    // need to define the iterator() method of Iterable
    // interface
    @Override public Iterator iterator()
    {
        return str.iterator();
    }
}
  
public class EmployeesTester {
    public static void main(String[] args)
    {
        Employees emps = new Employees();
        for (String st : emps.str) {
            System.out.println(st);
        }
    }
}
输出
practice
geeks
for
geeks
to
learn
coding

使用 remove() 方法从集合中删除项目

  • 它删除迭代器返回的集合的最后一个元素。
  • 如果迭代正在进行,同时底层集合被修改,则通过调用remove()方法,迭代器将抛出ConcurrentModificationException。

Java

// java program to remove()
// elements from a collection
  
import java.util.ArrayList;
import java.util.Iterator;
  
public class MyClass {
    public static void main(String[] args)
    {
          // create a list of Integers
        ArrayList numbers
            = new ArrayList();
        numbers.add(12);
        numbers.add(8);
        numbers.add(2);
        numbers.add(23);
            
          // get the iterator on the list
        Iterator it = numbers.iterator();
        while (it.hasNext()) {
                
              // gives the next element
              // and iterator moves to next 
              // element
            Integer i = it.next();
  
            if (i < 10) {
                    
                  // removes the current element
                it.remove(); 
            }
        }
        System.out.println(numbers);
    }
}
输出
[12, 23]

迭代器 forEachRemaining() 示例

Java

// Java program to show the usage of
// Iterator forEachRemaining()
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        //  initializing ArrayList
        List numbers
            = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80);
  
        numbers.iterator().forEachRemaining(
            System.out::println);
    }
}
输出
10
20
30
40
50
60
70
80

Java迭代器的优点:

  1. 它不是一个遗留接口,可以遍历整个集合,如 ArrayList、HashMap、TreeSet、HashSet 等。
  2. 它可用于任何Java集合,因此称为集合 API 的通用游标。
  3. 支持读取和删除操作。
  4. 简单易用的方法名称。

Java迭代器的局限性:

  1. 它不支持 CRUD(创建、读取、更新、删除)操作中的创建和更新操作。
  2. 它仅支持单向遍历,即转发方向。
  3. 与 Spliterator 相比,它不支持对大量数据进行更好的迭代。
  4. 它只支持顺序迭代,即它不支持并行迭代元素。

迭代器和枚举的区别:

Iterator

Enumeration

It was introduced in JDK 1.2.It was introduced in JDK 1.0.
It is a universal Cursor.i.e can be used in any java collections.It is not a universal cursor.i.e we can use it only for some legacy classes.
It supports both Read and Remove operations.It supports only Read operation.
It has simple method names.It has lengthy method names.
One can do any modification while traversing over the elements.We cannot do any modifications while traversing.
Not a legacy interface. Can traverse overall collections like ArrayList, HashMap, TreeSet, Vector etc.collectionsLegacy interface. Traverse only Vector, Hashtable.

方法:

                 Methods                               

           Type                                              Explanation  
       hasNext() boolean
  • If iteration has more elements, then it returns true.
  • If the iterator has gone through all the elements, it returns false
       next()E
  • It returns the next element of iteration.
  • It throws NoSuchElementException if the iterator has no more elements.
       remove()void
  • It removes the last element of the collection returned by the iterator.
  • If the iteration is in progress and meanwhile underlying collection is modified then by calling remove() method, iterator will throw an ConcurrentModificationException.
forEachRemaining()         E
  • It performs the given action for each remaining element until all elements have been processed.
  • If the order is specified, the actions are performed in the order of iteration.
  • It throws NullPointerException if the action is null.