Java Basics : Comparable vs Comparator
Difference
Comparable lets a class implement its own comparison:
- it's in the same class (it is often an advantage)
- there can be only one implementation (so you can't use that if you want two different cases)
- A comparable object is capable of comparing itself with another object. The class itself must implements the
java.lang.Comparable
interface in order to be able to compare its instances. - Comparable provides compareTo() method to sort elements.
- Comparable is found in java.lang package
- We can sort the list elements of Comparable type byCollections.sort(List) method.
By comparison, Comparator is an external comparison:
- it is typically in a unique instance (either in the same class or in another place)
- you name each implementation with the way you want to sort things
- you can provide comparators for classes that you do not control
- the implementation is usable even if the first object is null
- A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the
java.util.Comparator
interface - Comparator provides compare() method to sort elements
- Comparator is found in java.util package.
- We can sort the list elements of Comparator type byCollections.sort(List,Comparator) method.
Comparable Example
The Employee class where we are implementing Comparable
===========================================
public class Employee implements Comparable<Employee> {
String empName;
int empId;
public Employee(String empName, int empId )
{ super();
this.empId=empId;
this.empName=empName;
}
@Override
public int compareTo(Employee emp) {
return (this.empId<emp.empId)?-1 :(this.empId>emp.empId)?1:0;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}
=================================
The main Class
=================================
import java.util.*;
public class EmployeeComparableMain {
public static void main(String[] args) {
Employee e1= new Employee("Steve",1);
Employee e2= new Employee("Jack",2);
Employee e3= new Employee("Ram",5);
Employee e4= new Employee("Lova",3);
List<Employee> list = new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);
Iterator itr=list.iterator();
while(itr.hasNext())
{
Employee emp= (Employee) (itr.next());
System.out.println("Name :" +emp.getEmpName()+" Id=" +emp.empId );
}
Collections.sort(list);
itr=list.iterator();
while(itr.hasNext())
{
Employee emp= (Employee) (itr.next());
System.out.println("Name :" +emp.getEmpName()+" Id=" +emp.empId );
}
Collections.sort(list);
}
}
============
o/P
============
Name :Steve Id=1
Name :Jack Id=2
Name :Ram Id=5
Name :Lova Id=3
Name :Steve Id=1
Name :Jack Id=2
Name :Lova Id=3
Name :Ram Id=5
=================================================
For Comparator
We will create class country having attribute id and name and will create another class
CountrySortByIdComparator
which will implement Comparator interface and implement a compare method to sort collection of country object by id and we will also see how to use anonymous comparator.1.Country.java
public class Country{
int countryId;
String countryName;
public Country(int countryId, String countryName) {
super();
this.countryId = countryId;
this.countryName = countryName;
}
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
2.CountrySortbyIdComparator.java
package org.arpit.javapostsforlearning; import java.util.Comparator; //If country1.getCountryId()<country2.getCountryId():then compare method will return -1 //If country1.getCountryId()>country2.getCountryId():then compare method will return 1 //If country1.getCountryId()==country2.getCountryId():then compare method will return 0 public class CountrySortByIdComparator implements Comparator<Country>{ @Override public int compare(Country country1, Country country2) { return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ; } }
3.ComparatorMain.java
package org.arpit.javapostsforlearning; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ComparatorMain { /** * @author Arpit Mandliya */ public static void main(String[] args) { Country indiaCountry=new Country(1, "India"); Country chinaCountry=new Country(4, "China"); Country nepalCountry=new Country(3, "Nepal"); Country bhutanCountry=new Country(2, "Bhutan"); List<Country> listOfCountries = new ArrayList<Country>(); listOfCountries.add(indiaCountry); listOfCountries.add(chinaCountry); listOfCountries.add(nepalCountry); listOfCountries.add(bhutanCountry); System.out.println("Before Sort by id : "); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println("Country Id: "+country.getCountryId()+"||"+"Country name: "+country.getCountryName()); } Collections.sort(listOfCountries,new CountrySortByIdComparator()); System.out.println("After Sort by id: "); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName()); } //Sort by countryName Collections.sort(listOfCountries,new Comparator<Country>() { @Override public int compare(Country o1, Country o2) { return o1.getCountryName().compareTo(o2.getCountryName()); } }); System.out.println("After Sort by name: "); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName()); } } }
Output:
Before Sort by id : Country Id: 1||Country name: India Country Id: 4||Country name: China Country Id: 3||Country name: Nepal Country Id: 2||Country name: Bhutan After Sort by id: Country Id: 1|| Country name: India Country Id: 2|| Country name: Bhutan Country Id: 3|| Country name: Nepal Country Id: 4|| Country name: China After Sort by name: Country Id: 2|| Country name: Bhutan Country Id: 4|| Country name: China Country Id: 1|| Country name: India Country Id: 3|| Country name: Nepal
No comments:
Post a Comment