Zakk
Zakk

Reputation: 21

What is Comparable[] in Java?

I found a code where Comparable[] written preceding the array name a. I don't understood what's Comparable[] a and why Comparable[] needed to declare before an array name a.

public static void merge(Comparable[] a, int lo, int mid, int hi)
{
    // Merge a[lo..mid] with a[mid+1..hi].
    int i = lo, j = mid+1;
    for (int k = lo; k <= hi; k++) // Copy a[lo..hi] to aux[lo..hi].
        aux[k] = a[k];
    for (int k = lo; k <= hi; k++) // Merge back to a[lo..hi].
        if (i > mid) a[k] = aux[j++];
        else if (j > hi ) a[k] = aux[i++];
        else if (less(aux[j], aux[i])) a[k] = aux[j++];
        else a[k] = aux[i++];
}

Upvotes: 1

Views: 4797

Answers (1)

Ivan
Ivan

Reputation: 3836

In java type declarations precede variable names. E.g. String b means that b is an instance of String class. Java is statically an and strongly typed language.

So Comparable[] a says that a is an array of instances of some class implementing Comparable interface. Meaning each of the array's elements is either null or something, having compareTo method. See less method implementation and probably you'll find compareTo calls there.

A few examples of standard classes implementing comparable:

  • Integer, so new Integer[] {1, 2, 3, 4, 5} can be passed as a first argument to this function
  • Double, so new Double[] {1.5, 1.6, 1.8} can be passed as a first argument
  • String, so new String[] {"a", "b", "c"} can be passed as a first argument

Overall that construction allows to have the same piece of code handle different types adhering to a similar interface (meaning you don't have to write the same code for every new class you have). You can create some class implementing Comparable and reuse this code for this.

Also see Comparable JavaDoc.

Upvotes: 4

Related Questions