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

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

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

Java AbstractCollectioniterator()方法用于返回与 Collection 相同元素的迭代器。元素从集合中的内容以随机顺序返回。

句法:

Iterator iterate_value = AbstractCollection.iterator();

参数:该函数不带任何参数。

返回值:该方法迭代集合的元素并返回值(迭代器)。

下面的程序说明了 AbstractCollection.iterator() 方法的使用:

方案一:

// Java code to illustrate iterator()
  
import java.util.*;
import java.util.AbstractCollection;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Collection
        AbstractCollection
            abs = new TreeSet();
  
        // Use add() method to add
        // elements into the Collection
        abs.add("Welcome");
        abs.add("To");
        abs.add("Geeks");
        abs.add("4");
        abs.add("Geeks");
  
        // Displaying the Collection
        System.out.println("Collection: " + abs);
  
        // Creating an iterator
        Iterator value = abs.iterator();
  
        // Displaying the values
        // after iterating through the collection
        System.out.println("The iterator values are: ");
  
        while (value.hasNext()) {
  
            System.out.println(value.next());
        }
    }
}
输出:
Collection: [4, Geeks, To, Welcome]
The iterator values are: 
4
Geeks
To
Welcome

方案二:

// Java code to illustrate iterator()
  
import java.util.*;
import java.util.AbstractCollection;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
  
        // Creating an empty Collection
        AbstractCollection
            abs = new ArrayList();
  
        // Use add() method to add
        // elements into the Collection
        abs.add("Welcome");
        abs.add("To");
        abs.add("Geeks");
        abs.add("4");
        abs.add("Geeks");
  
        // Displaying the Collection
        System.out.println("Collection: " + abs);
  
        // Creating an iterator
        Iterator value = abs.iterator();
  
        // Displaying the values
        // after iterating through the collection
        System.out.println("The iterator values are: ");
  
        while (value.hasNext()) {
  
            System.out.println(value.next());
        }
    }
}
输出:
Collection: [Welcome, To, Geeks, 4, Geeks]
The iterator values are: 
Welcome
To
Geeks
4
Geeks