当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ConcurrentSkipListSet comparator()用法及代码示例



java.util.concurrent.ConcurrentSkipListSet的comparator()方法是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–



相关用法


注:本文由纯净天空筛选整理自NamanSingh34大神的英文原创作品 ConcurrentSkipListSet comparator() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。