Skip to main content

Comparator Vs Comarable

Comparable Interface

Comparable is an interface in java, which has only comparTo (Object Obj) method in it.
This is used to sort the user defined objects on specific member field.


When Comparable is preferred.

1. Having provision of modifying the User defined object to implement the Comparable interface. (Third party jar class objects doesn't have provision to modify).
2. Have a requirement to sort the User defined object by one Member field in their natural sorting order.
3. Comparable provides only one Sorting for an Object.

Our String and Wrapper Classes like Integer, Double, Long, BigDecimal etc. are override this compareTo method by implementing the Comparable Interface.


For example,
To sort the Bank Accounts  based on the amount it contains.

1. Create Account pojo with all the member fields including amount.
2. Implement the Account pojo with Comparable interface.
3. Override the compareTo(Object obj) method from Comparable interface. (Refer following code snippet)

Account POJO

package com.sbs.sort;

import java.math.BigDecimal;

public class Account implements Comparable<Account>{

    private BigDecimal ammount;
    private Long accountNumber;
    private String accountHolderName;
   
    public Account(BigDecimal ammount, Long accountNumber,
            String accountHolderName) {
        super();
        this.ammount = ammount;
        this.accountNumber = accountNumber;
        this.accountHolderName = accountHolderName;
    }

    public BigDecimal getAmmount() {
        return ammount;
    }

    public void setAmmount(BigDecimal ammount) {
        this.ammount = ammount;
    }

    public Long getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(Long accountNumber) {
        this.accountNumber = accountNumber;
    }

    public String getAccountHolderName() {
        return accountHolderName;
    }

    public void setAccountHolderName(String accountHolderName) {
        this.accountHolderName = accountHolderName;
    }

    @Override
    public int compareTo(Account o) {
        return this.ammount.compareTo(o.getAmmount());
    }
}

ComparableSortTest 

package com.sbs.sort;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableSortTest {

    public ComparableSortTest() {
    }
    public static List<Account> accountsList = new ArrayList<Account>();
   
    static
    {
        accountsList.add(new Account(new BigDecimal("200000"),10010l,"Bhargava Surimenu"));
        accountsList.add(new Account(new BigDecimal("20000"),100102l,"Satya Surimenu"));
        accountsList.add(new Account(new BigDecimal("100000"),100104l,"Hemachandra Surimenu"));
        accountsList.add(new Account(new BigDecimal("600000"),100106l,"Neha Surimenu"));
        accountsList.add(new Account(new BigDecimal("30000"),100108l,"Veeru Surimenu"));
        accountsList.add(new Account(new BigDecimal("700000"),100109l,"Venky Surimenu"));
    }
   
    public static void main(String[] args) {
       
        System.out.println("----- Accounts List Before Sort ------");
        System.out.println("Account   "+"Ammount");
        for(Account account:accountsList)
            System.out.println(account.getAccountNumber()+"   "+
                    account.getAmmount());
       
        //Sort
        Collections.sort(accountsList);
       
        System.out.println("----- Accounts List After Sorting ------");
       
        System.out.println("Account   "+"Ammount");
            for(Account sAccount:accountsList)
                System.out.println(sAccount.getAccountNumber()+"   "+
                        sAccount.getAmmount());
    }
}



Comparator Interface

Comparator is an interface in java, which has only compare(Object Obj) method in it.
This is used to sort the user defined objects on specific member field.


When Comparator is preferred.

1. Having no provision of modifying the User defined object
(Third party jar class objects doesn't have provision to modify).
2. Have a requirement to sort the User defined objects by various member fields in their natural sorting order.
3. Comparator interface provides multiple comparators (Sortings)for an Object.


For example,
To sort the Employee based on the employee number it contains.

1. Create Employee pojo with all the member fields including amount.
2. Create a Employe Comparator and Implement the with Comparator interface.
3. Override the compare(Object obj) method from Comparator interface. (Refer following code snippet).
4. Pass the employee Comparator as argument to the Sort method.

Employee 

package com.sbs.sort;

import java.math.BigDecimal;


public class Employee {

    public Employee() {
       
    }

   
    public Employee(String name,String number, BigDecimal salary) {
        super();
        this.name = name;
        this.number = number;
        this.salary = salary;
    }


    private String name;
    private String number;
    private BigDecimal salary;
   
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
   
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public BigDecimal getSalary() {
        return salary;
    }
    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
   
   
}

EmpComparator 

package com.sbs.sort;

import java.util.Comparator;

public class EmpComparator implements Comparator<Employee>{

     public EmpComparator() {
       
    }

    @Override
    public int compare(Employee emp1, Employee emp2) {
        return (emp1).getNumber().compareTo(emp2.getNumber());
    }
}


ComparatorSortTest
 
package com.sbs.sort;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorSortTest {

    public ComparatorSortTest() {
       
    }
   
    public static List<Employee> employeeList = new ArrayList<Employee>();
    static
    {   
       
        employeeList.add(new Employee("Bhargava Surimenu","SBS101",new BigDecimal("1000")));
        employeeList.add(new Employee("Satya Surimenu","SBS108",new BigDecimal("2000")));
        employeeList.add(new Employee("Hemachandra Surimenu","SBS106",new BigDecimal("6000")));
        employeeList.add(new Employee("Satya Surimenu","SBS105",new BigDecimal("7000")));
        employeeList.add(new Employee("Neha Surimenu","SBS107",new BigDecimal("8000")));
        employeeList.add(new Employee("Veeru Surimenu","SBS102",new BigDecimal("3000")));
        employeeList.add(new Employee("Venky Surimenu","SBS104",new BigDecimal("1000")));
       
    }
   
    public static void main(String[] args) {
       
        System.out.println("----- Employees List Before Sort ------");
        System.out.println("Number   "+"Name");
        for(Employee emp:employeeList)
            System.out.println(emp.getNumber()+"   "+
                    emp.getName());
       
        //Passing EmpComparator as argument
        Collections.sort(employeeList,new EmpComparator());
       
        System.out.println("----- Employees List After Sorting ------");
       
        System.out.println("Number   "+"Name");
        for(Employee emp:employeeList)
            System.out.println(emp.getNumber()+"   "+
                    emp.getName());
    }
}

Comments

Popular posts from this blog

Connection Time out Vs Socket Time out

Time out Any client(or source) which is unable to connect to the server (or Destination) in a specified time, then requests will automatically gets time outs. Port Port numbers allow different applications on the same computer to utilize network resources without interfering with each other. Port numbers most commonly appear in network programming, particularly socket programming. Sometimes, though, port numbers are made visible to the casual user. For example, some Web sites a person visits on the Internet use a URL like the following: http://www.appdomain.in:80/ In this example, the number 80 refers to the port number used by the Web browser to connect to the Web server. Normally, a Web site uses port number 80 and this number need not be included with the URL (although it can be). Port 80 is the default port for HTTP Socket Each and every communication from one application to another application should happen through sockets. Socket is gateway to send/receive information from one a...

"immutability" Nature of an Object

Immutability. A Java object is considered to be immutable when its state (properties and contents) cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable Immutable objects are simple to use test and construct. Immutable objects are thread-safe by default. Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection). This is the reason most of the times we prefer String objects as Key in many Map Collection objects. Immutable objects do not require an implementation of clone. Immutable objects allow hashCode to use lazy initialization, and to cache its return value. To crea...

Self Signed Certificates Vs Signed Certificates (CA Certificates)

Certificates Certificates basically two categories. Self Signed Certificates  - will create by self CA Certificates  - will be  provided by Third party vendor with robust algorithms Depends on the location of installing the certificate these are two types 1. Public Key Certificates (Client Side) 2. Private Key Certificates (Server Side) Self Signed Certificates   If any one is using self signed certificates in their applications they have to make sure both server side and client side certificates are in sync. Other wise we should be ready to face SSLHandShake Exceptions. These will be preferable mostly for lower environments not for production. CA certificates  If you install CA certificates on server side, client side certificates are installed automatically whenever they access the server. So in production for CA certificates there is no need to install the client side certificates. We can generate a Self Signed Certificate using Java Key tool JAVA_HOME/bi...