Comparator vs Comparable Interface in java ?

Comparator vs Comparable


* Comparator 


  - Its Interface and Functional Interface

  - Its an Functional Interface it means we can use anonymous Inner class and Lambda Expressions

  - Comparator has non abstract method which is " int compare(int , int) "

  - It take 2 Type class Objects (Ex: int compare(Integer i , Integer j))

  - All Wrapper Classes has " .compare(type , type) " method which returns int value 

  - if returns positive integer it means swap if negative it means no swap if zero it means both are equal

  - Comparator is as a third person who are comparing objects and generates logic

  - But Collections.sort(Type , comparator obj ) ye sort krta hai according Comparator (compare(T,T))



* Comparable


  - Comparable is Normal Interface

  - It has method name " int compareTo(Type object) " 

  - There are 2 types of compareTo(Type obj) and compareTo(String obj)

  - (1) - compareTo(Type obj) it just gives class freedom that the class compare objects by their own

  - (2) - .compareTo(String obj) it check string lexicographically ("Ndk".compareTo(""Ysh))

- if return positive int value it means "Ndk" is Greater

- if return negative int value it means "Ysh" is Greater

- if return zero it means both Strings are Equals

  - Custom class must have to implement comparable interface (cause all  Wrapper Classes implement comparable interface)

  - Thats why its not FunctionalInterface

  - Comparable is like he gives feature to class that it can compare itself by own  

Comments

Popular posts from this blog

Collection Framework of Java

What is DBMS ?

Compiler vs Interpreter vs JIT Compiler