📌  相关文章
📜  Java中的 ConcurrentSkipListSet 比较器() 方法及示例

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

Java中的 ConcurrentSkipListSet 比较器() 方法及示例


Java .util.concurrent.ConcurrentSkipListSetcomparator()方法是Java中的一个内置函数,它返回用于对给定集合中的元素进行排序的比较器。如果使用自然排序,则返回 null。

句法:

public Comparator comparator()

这里 E 是类型参数,即集合维护的元素的类型。

返回值:该函数返回用于对给定集合中的元素进行排序的比较器,如果使用自然排序,则返回 null。

下面给出的程序说明了 ConcurrentSkipListSet.comarator() 方法:

方案一:

// Java program to demonstrate comparator()
// method of ConcurrentSkipListSet
  
import java.util.concurrent.*;
  
class ConcurrentSkipListSetcomparatorExample1 {
    public static void main(String[] args)
    {
        // Creating first set object
        ConcurrentSkipListSet set1
            = new ConcurrentSkipListSet();
  
        // Creating second set object
        ConcurrentSkipListSet set2
            = new ConcurrentSkipListSet();
  
        // Adding elements to first set
        set1.add(30);
        set1.add(5);
        set1.add(50);
        set1.add(20);
  
        // Ordering the elements in descending order
        set2 = (ConcurrentSkipListSet)
                   set1.descendingSet();
  
        // Displaying the contents of the set1
        System.out.println("Contents of the set1: "
                           + set1);
  
        // Displaying the contents of the set2
        System.out.println("Contents of the set2: "
                           + set2);
  
        // Retrieving the comparator
        // used for ordering of elements
        System.out.println("The comparator"
                           + " used in the set:\n"
                           + set2.comparator());
    }
}
输出:
Contents of the set1: [5, 20, 30, 50]
Contents of the set2: [50, 30, 20, 5]
The comparator used in the set:
java.util.Collections$ReverseComparator@74a14482

方案二:

// Java program to demonstrate comparator()
// method of ConcurrentSkipListSet
  
import java.util.concurrent.*;
  
class ConcurrentSkipListSetcomparatorExample2 {
    public static void main(String[] args)
    {
        // Creating first set object
        ConcurrentSkipListSet set1
            = new ConcurrentSkipListSet();
  
        // Adding elements to first set
        set1.add(30);
        set1.add(5);
        set1.add(50);
        set1.add(20);
  
        // Displaying the contents of the set1
        System.out.println("Contents of the set1: "
                           + set1);
  
        // Retrieving the comparator
        // used for ordering of elements
        System.out.println("The comparator used in the set: "
                           + set1.comparator());
    }
}
输出:
Contents of the set1: [5, 20, 30, 50]
The comparator used in the set: null

参考: https: Java/util/concurrent/ConcurrentSkipListSet.html#comparator–