Definition Of Comparator Interface

Definition Of Comparator Interface

Definition Of Comparator Interface ~ First of all, before reading this post you should understand what is an interface in craftingez6-coding.

You can found comparator interface in java.util.package and it contains 2 methods. Thus 2 of those methods are : .compare(obj1, obj2) and equals(Object element)

compare() method

public int compare(object1, object2)

Java Comparator Example (non-generic style)

Thus for this example I’ve created 2 class of sorting elements in the base of age and name. Due to the sake of simplicity of this article i’ve only created 2 :

  1. Age Comparator
  2. Name Comparator

Continue reading Definition Of Comparator Interface

What is a Comparable Interface?

What is a Comparable Interface?

What is a comparable interface – Coders can also order objects using java comparable interface. And rather than any type of class for that object. As a result, java uses user-defined class for this interface.

You can find java comparable interface inside the java.lang package since it is located inside that package. Therefore it contains only 1 method which seems like to be CompareTo(objects). Furthermore the interface provides single sorting element on a single data member only. So For an example it may be rollno, name, age or anything else.

compareTo(Object obj) method

Therefore to compare the current object with the specified object we used the syntax :

public int compareTo(Object obj)

Hence, Here is a list of what the element we can sort :

Continue reading What is a Comparable Interface?