當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。