When to use Comparable interface in Java?

When to use Comparable interface in Java?

Comparable interfaces in java can be used to perform sorting operations/sort the elements in the collections. It is mainly used for basic level of sortings. You can use comparable interface to perform single sorting sequences.

 

If you have a model (say Mobile) with around 3 to 5 fields(model, simcount,memory, price) then using comparable you can sort using any one of the field.

 

Understand clearly: You can sort using simcount/price/model etc…. But finally you can choose only one way of sorting. Since comparable will be implemented in the own class, it will have only one compareTo() method, where you can provide only one way sorting sequence.


Collecitions.sort(Collection)

 

Where as in comparator, you are allowed to sort using any number of fields, because we can create a separate class only for sorting by implementing comparator. This way you can create any number of classes each with different implementations.

 


Collecitions.sort(Collection,COMPARATOR_CLASS);

 

Comparable interface in Java:

If we see String class in the jdk source code, it is implemented with the Comparable interface.


public final class String
implements java.io.Serializable, Comparable<String>, CharSequence

[/java]

 

So String with TreeSet or Collections or Arrays classes also perform the sorting using the comparable interface only.

 

Comparable interface sorts the string elements in the natural order/lexicographical order.

lexicographical order: Comparing each character unicode value/decimal value of the given strings.

 

How comparable works in Java ?

What is lexicographical order in Java ?

Example for lexicographical order in Java ?

 

String with Comparable interface:

Is it possible to override String’s compareTo method ?

No. Because String is a final class, so we can’t override compareTo method.

But you can implement comparable interface in your own class and override the compareTo method as per your need.

 

Understand clearly that compareTo is a method exist in the Comparable interface. so when you implement Comparable interfaceyou must provide some implementation to compareTo() method.

 

Comparable interface example in Java: 

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

public class Mobile implements Comparable<Mobile> {

String modelName;

int simCount;

int price;

String memoryCardUpto;

public String getModelName() {
return modelName;
}

public void setModelName(String modelName) {
this.modelName = modelName;
}

public int getSimCount() {
return simCount;
}

public void setSimCount(int simCount) {
this.simCount = simCount;
}

public int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

public String getMemoryCardUpto() {
return memoryCardUpto;
}

public void setMemoryCardUpto(String memoryCardUpto) {
this.memoryCardUpto = memoryCardUpto;
}

public static void main(String[] args) {
List<Mobile> allMobiles = new ArrayList<Mobile>();

Mobile m1 = new Mobile();
m1.setModelName("Nokia 105");
m1.setPrice(1500);
m1.setSimCount(1);
m1.setMemoryCardUpto("16GB");

allMobiles.add(m1);

Mobile m2 = new Mobile();
m2.setModelName("Nokia 130");
m2.setPrice(1700);
m2.setSimCount(2);
m2.setMemoryCardUpto("32GB");

allMobiles.add(m2);

Mobile m3 = new Mobile();
m3.setModelName("iPhone 6+");
m3.setPrice(70000);
m3.setSimCount(1);
m3.setMemoryCardUpto("128GB");
allMobiles.add(m3);

Mobile m4 = new Mobile();
m4.setModelName("Xiaomi MI");
m4.setPrice(6000);
m4.setSimCount(2);
m4.setMemoryCardUpto("32GB");
allMobiles.add(m4);

// Before sorting
System.out.println("Before Sorting");
for (Mobile mobile : allMobiles) {
System.out.println("Model: " + mobile.getModelName() + " | Memory: " + mobile.getMemoryCardUpto()
+ " | Price:" + mobile.getPrice() + " | SimCount: " + mobile.getSimCount());
}

Collections.sort(allMobiles);

System.out.println("\n\n\n");
System.out.println("After Sorting");
// after sorting
for (Mobile mobile : allMobiles) {
System.out.println("Model: " + mobile.getModelName() + " | Memory: " + mobile.getMemoryCardUpto()
+ " | Price:" + mobile.getPrice() + " | SimCount: " + mobile.getSimCount());
}
}

@Override
public int compareTo(Mobile o) {
return o.price - this.getPrice();
}
}

 

Output:


Before Sorting
Model: Nokia 105 | Memory: 16GB | Price:1500 | SimCount: 1
Model: Nokia 130 | Memory: 32GB | Price:1700 | SimCount: 2
Model: iPhone 6+ | Memory: 128GB | Price:70000 | SimCount: 1
Model: Xiaomi MI | Memory: 32GB | Price:6000 | SimCount: 2

After Sorting
Model: iPhone 6+ | Memory: 128GB | Price:70000 | SimCount: 1
Model: Xiaomi MI | Memory: 32GB | Price:6000 | SimCount: 2
Model: Nokia 130 | Memory: 32GB | Price:1700 | SimCount: 2
Model: Nokia 105 | Memory: 16GB | Price:1500 | SimCount: 1

 

Price details Ascending order:


@Override
public int compareTo(Mobile o) {
return this.price - o.getPrice();
}

 

Output:

Before Sorting
Model: Nokia 105 | Memory: 16GB | Price:1500 | SimCount: 1
Model: Nokia 130 | Memory: 32GB | Price:1700 | SimCount: 2
Model: iPhone 6+ | Memory: 128GB | Price:70000 | SimCount: 1
Model: Xiaomi MI | Memory: 32GB | Price:6000 | SimCount: 2
After Sorting
Model: Nokia 105 | Memory: 16GB | Price:1500 | SimCount: 1
Model: Nokia 130 | Memory: 32GB | Price:1700 | SimCount: 2
Model: Xiaomi MI | Memory: 32GB | Price:6000 | SimCount: 2
Model: iPhone 6+ | Memory: 128GB | Price:70000 | SimCount: 1

 

Sorting based on simcount:


@Override
public int compareTo(Mobile o) {
return this.simCount - o.getSimCount();
}

 

Output:


Before Sorting
Model: Nokia 105 | Memory: 16GB | Price:1500 | SimCount: 1
Model: Nokia 130 | Memory: 32GB | Price:1700 | SimCount: 2
Model: iPhone 6+ | Memory: 128GB | Price:70000 | SimCount: 1
Model: Xiaomi MI | Memory: 32GB | Price:6000 | SimCount: 2
After Sorting
Model: Nokia 105 | Memory: 16GB | Price:1500 | SimCount: 1
Model: iPhone 6+ | Memory: 128GB | Price:70000 | SimCount: 1
Model: Nokia 130 | Memory: 32GB | Price:1700 | SimCount: 2
Model: Xiaomi MI | Memory: 32GB | Price:6000 | SimCount: 2

 

Sorting based on memoryUpto[String]:

@Override
public int compareTo(Mobile o) {
return this.memoryCardUpto.compareTo(o.memoryCardUpto);
}

 

Output:


Before Sorting
Model: Nokia 105 | Memory: 16GB | Price:1500 | SimCount: 1
Model: Nokia 130 | Memory: 32GB | Price:1700 | SimCount: 2
Model: iPhone 6+ | Memory: 128GB | Price:70000 | SimCount: 1
Model: Xiaomi MI | Memory: 32GB | Price:6000 | SimCount: 2
After Sorting
Model: iPhone 6+ | Memory: 128GB | Price:70000 | SimCount: 1
Model: Nokia 105 | Memory: 16GB | Price:1500 | SimCount: 1
Model: Nokia 130 | Memory: 32GB | Price:1700 | SimCount: 2
Model: Xiaomi MI | Memory: 32GB | Price:6000 | SimCount: 2

Here strings are compared using the lexicographical order.
So only after 128GB, 16GB comes.

 

How Comparable compares int and String variables ?

int: You can compare using less than,equal and greater than operators.

String: You can not use any of the comparison operators/it will compare based on lexicographical order. [means only with compareTo method]

 

Limitation of Comparable Interface:

We can able to sort based on any one field. Where as we will get a scenario to compare more than one field, then we have to go with comparator.

 

 

 

618 total views, 1 views today

About: Mirthbees

Blogger, Innovator, Developer and Enterpreneur. Founder of GuruRecharge, Readymade online recharge script. Lead Developer in Bookrate.in