Java AbstractCollection中的iterator()方法及示例
Java AbstractCollection的iterator()方法用于返回与集合中相同元素的迭代器。返回的元素顺序与集合中的顺序不同。
语法:
Iterator iterate_value = AbstractCollection.iterator();
参数:
此函数不接受任何参数。
返回值:
该方法遍历集合的元素并返回值(迭代器)。
以下程序说明了AbstractCollection.iterator()方法的使用:
程序1:
// 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<String>
abs = new TreeSet<String>();
// 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
程序2:
// 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<String>
abs = new ArrayList<String>();
// 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