Saturday 19 April 2014

TreeSet : comparator : Get the Comparator used

public Comparator<? super E> comparator()
Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.

class Employee1{
 Integer number;
 String name;
 
 Employee1(int number, String  name){
  this.number = number;
  this.name = name;
 } 
 
 public String toString(){
  return number + " " + name;
 }
 
}

import java.util.Comparator;
class EmployeeIdComparator implements Comparator<Employee1>{

 public int compare(Employee1 e1, Employee1 e2){
  return e1.number.compareTo(e2.number);
 }
 
 public String toString(){
  return "EmployeeIdComparator";
 }
 
}

import java.util.Comparator;

class EmployeeNameComparator implements Comparator<Employee1>{

 public int compare(Employee1 e1, Employee1 e2){
  return e1.name.compareTo(e2.name);
 } 
 
 public String toString(){
  return "EmployeeNameComparator";
 }
 
}

import java.util.*;

class TreeSetComparator{
 public static void main(String args[]){
  TreeSet<Employee1> mySet1;
  TreeSet<Employee1> mySet2;
  TreeSet<Employee1> mySet3;
  
  mySet1 = new TreeSet<> (new EmployeeNameComparator());
  mySet2 = new TreeSet<> (new EmployeeIdComparator());
  mySet3 = new TreeSet<> ();
  
  System.out.print("Comparator used for mySet1 is ");
  System.out.println(mySet1.comparator());
  System.out.print("Comparator used for mySet2 is ");
  System.out.println(mySet2.comparator());
  System.out.print("Comparator used for mySet3 is ");
  System.out.println(mySet3.comparator()); 
 }
}

Output
Comparator used for mySet1 is EmployeeNameComparator
Comparator used for mySet2 is EmployeeIdComparator
Comparator used for mySet3 is null




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment