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

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

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

语法

public Comparator<E> comparator()

这里E是类型参数,即集合所保持的元素的类型。

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

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

程序1 :

// 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<Integer> set1
            = new ConcurrentSkipListSet<Integer>();
  
        // Creating second set object
        ConcurrentSkipListSet<Integer> set2
            = new ConcurrentSkipListSet<Integer>();
  
        // 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<Integer>)
                   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

程序2

// 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<Integer> set1
            = new ConcurrentSkipListSet<Integer>();
  
        // 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://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListSet.html#comparator-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程