Java中的 CopyOnWriteArraySet iterator() 方法
CopyOnWriteArraySet的iterator()方法以正确的顺序返回此 Set 中元素的迭代器。迭代器不支持 remove 方法。
句法:
public Iterator iterator()
返回值:该函数返回 Set 中元素的迭代器。
下面的程序说明了上述函数:
方案一:
// Java Program to illustrate the CopyOnWriteArraySet
// iterator() method in Java
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create object of CopyOnWriteArraySet
CopyOnWriteArraySet ArrSet
= new CopyOnWriteArraySet();
// Add elements
ArrSet.add(32);
ArrSet.add(67);
ArrSet.add(67);
ArrSet.add(100);
// print CopyOnWriteArraySet
System.out.println("CopyOnWriteArraySet: "
+ ArrSet);
// Call iterator() method of
Iterator iteratorVals = ArrSet.iterator();
// Print elements of iterator
// created from CopyOnWriteArraySet
System.out.println("\nThe iterator values of "
+ "CopyOnWriteArraySet are:\n");
// prints the elements using an iterator
while (iteratorVals.hasNext()) {
System.out.println(iteratorVals.next());
}
}
}
输出:
CopyOnWriteArraySet: [32, 67, 100]
The iterator values of CopyOnWriteArraySet are:
32
67
100
方案二:
// Java Program to illustrate the CopyOnWriteArraySet
// iterator() method in Java
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create object of CopyOnWriteArraySet
CopyOnWriteArraySet ArrSet
= new CopyOnWriteArraySet();
// Add elements
ArrSet.add("gopal");
ArrSet.add("gfg");
ArrSet.add("jgec");
ArrSet.add("sudo");
// print CopyOnWriteArraySet
System.out.println("CopyOnWriteArraySet: "
+ ArrSet);
// Call iterator() method of
Iterator iteratorVals = ArrSet.iterator();
// Print elements of iterator
// created from CopyOnWriteArraySet
System.out.println("\nThe iterator values of "
+ "CopyOnWriteArraySet are:\n");
// prints the elements using an iterator
while (iteratorVals.hasNext()) {
System.out.println(iteratorVals.next());
}
}
}
输出:
CopyOnWriteArraySet: [gopal, gfg, jgec, sudo]
The iterator values of CopyOnWriteArraySet are:
gopal
gfg
jgec
sudo
参考: https: Java/util/concurrent/CopyOnWriteArraySet.html#iterator–