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


Java java.util.TreeSet.comparator()用法及代碼示例


描述

這個comparator()方法返回用於對該集合中的元素進行排序的比較器,如果該集合使用其元素的自然排序,則返回 null。

聲明

以下是聲明java.util.TreeSet.comparator()方法。

public Comparator<? super E> comparator()

參數

NA

返回值

該方法調用返回用於對該集合中的元素進行排序的比較器,如果該集合使用其元素的自然排序,則返回 null。

異常

NA

示例

下麵的例子展示了 java.util.TreeSet.comparator() 方法的用法。

package com.tutorialspoint;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetDemo {
   public static void main(String[] args) {

      // creating TreeSet 
      TreeSet <Integer>tree = new TreeSet<Integer>();
      TreeSet <Integer>treecomp = new TreeSet<Integer>();

      // adding in the tree
      tree.add(12);
      tree.add(13);
      tree.add(14);
      tree.add(15);
      tree.add(16);
      tree.add(17);

      // using comparator
      treecomp = (TreeSet)tree.comparator();

      if(treecomp!=null) {
         for (Integer element:treecomp)
         System.out.println(element + " ");
      } else {
         System.out.println("treecomp value:"+treecomp); 
         System.out.println("So it is using natural ordering");
      }
   }    
}

讓我們編譯並運行上麵的程序,這將產生以下結果。

treecomp value:null
So it is using natural ordering

相關用法


注:本文由純淨天空篩選整理自 java.util.TreeSet.comparator() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。