目录

Comparator<? super E> comparator()

描述 (Description)

comparator()方法返回用于对此set中的元素进行排序的比较器,如果此set使用其元素的自然顺序,则返回null。

声明 (Declaration)

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

public Comparator<? super E> comparator()

参数 (Parameters)

NA

返回值 (Return Value)

方法调用返回用于对此集合中的元素进行排序的比较器,如果此集合使用其元素的自然顺序,则返回null。

异常 (Exception)

NA

例子 (Example)

以下示例显示了java.util.TreeSet.comparator()方法的用法。

package com.iowiki;
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
↑回到顶部↑
WIKI教程 @2018