How Comparable Interface works in Java ?

How comparable interface works in Java ?

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

 

[java]

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.
Here, in the below program we are going to compare “a” and “A”.

As we know string is implemented with the comparable interface by default, it will compare the decimal value of a(97) with A(65). So it prints either -32 or 32 based
on the comparison order.

Lexicographical order Java Example Program:

[java]
public class JavaSort {

public static void main(String[] args) {
String firstStr = "A";
// Decimal value of A => 65

String secString = "a";
// Decimal value of a => 97
// for all the values you can refer here,
//http://www.asciitable.com/

System.out.println(firstStr.compareTo(secString));
// 65 – 97 => -32
System.out.println(secString.compareTo(firstStr));
// 97-65 => 32

}

}

[/java]

output:

[plain]

-32
32

[/plain]

 

If suppose you are going to compare “A12” and “A11”,
As per the table, “A12”,

A => 65
1 => 49
2 => 50
Same way for “A11”
A => 65
1 => 49
1 => 49

 

Refer here for ASCII table values[Decimal values]

Now first two characters of both the strings are(“A1”) same, so it will directly start comparing the next character. that is (“2” from “A12” and “1” from “A11”).
So output is again,
50-49 => 1

 

 

Lexicographical order Java Example Program 1:

[java]

public class JavaSort {

public static void main(String[] args) {

String firstStr = "A12";

String secString = "A11";
System.out.println(firstStr.compareTo(secString));

System.out.println(secString.compareTo(firstStr));

}

}

[/java]

 

Output:

[plain]

1
-1

[/plain]

Leave a Reply