The Artima Developer Community
Sponsored Link

Java Buzz Forum
comparable vs comparator in java example

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
instanceof java

Posts: 576
Nickname: instanceof
Registered: Jan, 2015

instanceof java is a java related one.
comparable vs comparator in java example Posted: May 16, 2015 7:26 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by instanceof java.
Original Post: comparable vs comparator in java example
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Latest Java Buzz Posts
Latest Java Buzz Posts by instanceof java
Latest Posts From Instance Of Java

Advertisement
  • One of the common interview question What are the differences between comparable and comparator and how to sort collections using these interfaces ?
  • What are the differences between comparable and comparator and how to sort employee object by empId or empName using these interfaces.
  • Before discussing about differences lets see brief description about these two interfaces

Comparable Interface:

  • Comparable Interface is actually from java.lang package.
  • It will have a method compareTo(Object obj)to sort objects
  • public int compareTo(Object obj){ }
  • Comparable interface used for natural sorting these is the reason all wrapper classes and string class implementing this comparator and overriding compareTo(Object obj) method.
  • So in String and all wrapper classes compareTo(Object  obj) method is implemented in such way that it will sort all objects.

String class:

  • If we observe String class it is implementing comparable interface.
  • If compareTo(String str) methods returns 0 : both strings are equal
  • If compareTo(String str) method returns 1: string is lexicographically greater than the string argument
  • If compareTo(String str) method returns -1: string is lexicographically less than the string argument

  1. package java.lang;
  2.  
  3. public final class String
  4. extends Object
  5. implements Serializable, Comparable<String>, CharSequence {
  6.   
  7. public int compareTo(String anotherString){
  8.  //logic
  9. }
  10. }

Comparing String Objects:

  •  Lets see an example java program that will explains how two string objects are compared using compareTo(String str) method in String class.


  1. package com.instanceofjava;
  2. public class StringCompareDemo {
  3. public static void main(String [] args){
  4.    
  5.  String str1="comparable";
  6.  String str2="comparator";
  7.  
  8. int value=str1.compareTo(str2);
  9.  
  10. if(value==0){
  11.  
  12. System.out.println("Strings are equal");
  13.  
  14. }
  15. else{
  16.  
  17. System.out.println("Strings are not equal");
  18.  
  19. }
  20.  
  21. }
  22. }

Output:

  1. Strings are not equal

Wrapper classes:

  • Wrapper classes is used to convert primitive data values into java objects. for 8 primitive data types java has 8 corresponding wrapper classes. All these classes implementing comparable interface.
  • Lets see an example on Integer wrapper class 

Integer:


  1. package java.lang;
  2. public final class Integer
  3. extends Number
  4. implements Comparable<Integer> {
  5.   
  6. public int compareTo(Integer i){
  7.  //
  8. }
  9. }

  •  Lets see an example program of comparing two integer objects

  1. package instanceofjava;
  2.  
  3. public class IntegerComparableDemo {
  4.  
  5. public static void main(String [] args){
  6.  
  7.    // compares two Integer objects numerically
  8.  
  9.    Integer obj1 = new Integer("37");
  10.    Integer obj2 = new Integer("37");
  11.  
  12.    int retval =  obj1.compareTo(obj2);
  13.  
  14. if(retval > 0) {
  15.  
  16.    System.out.println("obj1 is greater than obj2");
  17. }
  18.  
  19. else if(retval < 0) {
  20.  
  21.  System.out.println("obj1 is less than obj2");
  22.  
  23.  }
  24.  else {
  25.  
  26.  System.out.println("obj1 is equal to obj2");
  27.  
  28. }
  29.  
  30. }

Output:
  1. obj1 is equal to obj2;

Sorting Collections using Comparator:

  •  By using Collections.sort(list); method we can sort objects in natural object sorting order 
  • An example program on Collections.sort(list); 
  • Sorting Employee objects by id.



  1. package instanceofjava;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class Employee implements  Comparable {
  8.  
  9.     String name;
  10.     int id;
  11.  
  12.  public String getName() {
  13.         return name;
  14.  }
  15.  
  16.  public void setName(String name) {
  17.         this.name = name;
  18.  }
  19.  
  20. public int getId() {
  21.  
  22.        return id;
  23.  }
  24.  
  25. public void setId(int id) {
  26.         this.id = id;
  27. }
  28.  
  29.  public Employee(String name, int id) {
  30.         this.name=name;
  31.         this.id=id;
  32. }
  33.  
  34.  @Override
  35.  public int compareTo(Object in) {
  36.         return  new Integer(this.id).compareTo(((Employee)in).id);
  37.   }
  38.  public static void main(String[] args) {
  39.  
  40.         Employee e1= new Employee("xyz", 37);
  41.         Employee e2= new Employee("abc", 46);
  42.         Employee e3= new Employee("sai", 38);
  43.  
  44.         ArrayList al= new ArrayList();
  45.  
  46.         al.add(e1);
  47.         al.add(e2);
  48.         al.add(e3);
  49.         Collections.sort(al);
  50.         Iterator itr= al.iterator();
  51.  
  52.      while (itr.hasNext()) {
  53.             Employee em = (Employee) itr.next();
  54.             System.out.println(em.getId()+" "+em.getName());            
  55.        }
  56. }
  57. }
     
Output:

  1. 37 xyz
  2. 38 sai
  3. 46 abc

Comparator:

  • Comparator Interface is actually from java.util package.
  • It will have a method compare(Object obj1, Object obj2)to sort objects
  • public int  compare(Object obj1, Object obj2){ }
  • Comparator interface used for customized sorting.
  • An example program which will sort employee objects by name

 

 1.Employee.java

  1. package instanceofjava;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class Employee  {
  8.  
  9.     String name;
  10.     int id;
  11.  
  12.  public String getName() {
  13.         return name;
  14.  }
  15.  
  16.  public void setName(String name) {
  17.         this.name = name;
  18.  }
  19.  
  20. public int getId() {
  21.  
  22.        return id;
  23.  }
  24.  
  25. public void setId(int id) {
  26.         this.id = id;
  27. }
  28.  
  29.  public Employee(String name, int id) {
  30.         this.name=name;
  31.         this.id=id;
  32. }
  33.  
  34.  
  35.  public static void main(String[] args) {
  36.  
  37.         Employee e1= new Employee("xyz", 37);
  38.         Employee e2= new Employee("abc", 46);
  39.         Employee e3= new Employee("sai", 38);
  40.  
  41.         ArrayList al= new ArrayList();
  42.  
  43.         al.add(e1);
  44.         al.add(e2);
  45.         al.add(e3);
  46.        Collections.sort(al, new EmpSortByName());
  47.         Iterator itr= al.iterator();
  48.  
  49.      while (itr.hasNext()) {
  50.             Employee em = (Employee) itr.next();
  51.             System.out.println(em.getId()+" "+em.getName());            
  52.        }
  53. }
  54. }

EmpSortByName.java:

 

  1. package instanceofjava;
  2. import java.util.Comparator;
  3. public class EmoSortByName implements Comparator<Employee> {
  4.  
  5.     @Override
  6.     public int compare(Employee arg0, Employee arg1) {
  7.         return arg0.getName().compareTo(arg1.getName());
  8.     }
  9.  
  10. }
     
Output:

  1. 46 abc
  2. 38 sai
  3. 37 xyz


Read: comparable vs comparator in java example

Topic: Learn Java from the ground up Previous Topic   Next Topic Topic: 9 programming languages and the women who created them

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use