Comparator<?
super E> comparator()
Return 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 SortedSetComparator{ public static void main(String args[]){ SortedSet<Employee1> mySet1; SortedSet<Employee1> mySet2; SortedSet<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
No comments:
Post a Comment