📌  相关文章
📜  Java中的 CopyOnWriteArraySet spliterator() 方法

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

Java中的 CopyOnWriteArraySet spliterator() 方法

CopyOnWriteArraySetspliterator()方法以正确的顺序在此 Set 中的元素上返回一个拆分器。在分离器上操作时不需要同步。

句法:

public Spliterator spliterator()

返回值:该函数返回集合中元素的拆分器

下面的程序说明了上述函数:

方案一:

// Java Program to illustrate the CopyOnWriteArraySet
// spliterator() 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);
  
        Spliterator
            numbers = ArrSet.spliterator();
  
        // print result from Spliterator
        System.out.println("Set of Numbers:");
  
        // forEachRemaining method  of Spliterator
        numbers
            .forEachRemaining(
                (n) -> System.out.println(n));
    }
}
输出:
CopyOnWriteArraySet: [32, 67, 100]
Set of Numbers:
32
67
100

方案二:

// Java Program to illustrate the CopyOnWriteArraySet
// spliterator() 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);
  
        Spliterator
            numbers = ArrSet.spliterator();
  
        // print result from Spliterator
        System.out.println("Set of strings:");
  
        // forEachRemaining method  of Spliterator
        numbers
            .forEachRemaining(
                (n) -> System.out.println(n));
    }
}
输出:
CopyOnWriteArraySet: [gopal, gfg, jgec, sudo]
Set of strings:
gopal
gfg
jgec
sudo

参考: https: Java/util/concurrent/CopyOnWriteArraySet.html#spliterator–