0

Here is a code of a sort class which I am implementing.

public class Insertion {
public static void sort(Comparable[] arr) {
    for (int i = 0; i < arr.length; i++) {
        int temp = i;
        while (temp > 0 && less(arr[temp], arr[temp - 1])) {
            exch(arr, temp, temp - 1);
            temp--;
        }
    }
}

public static void exch(Comparable[] arr, int i, int j) {
    Comparable temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

public static boolean less(Comparable i, Comparable j) {
    return i.compareTo(j) < 0;
}}

Here I'm not able to understand how the comparable interface is used without type parameters.

Suppose I want to pass a class Point which implements Comparable. Here it is

public class Point implements Comparable<Point> {
private final int x;
private final int y;


Point(int a, int b) {
    this.x = a;
    this.y = b;
}

public int getX() {
    return this.x;
}

public int getY() {
    return this.y;
}

public int compareTo(Point p) {
    return Integer.compare(this.x, p.x);
}}

And here is the test code i'm testing with

public class Test {
public static void main(String[] args) {
    Point[] pts = new Point[5];
    pts[0] = new Point(1, 2);
    pts[1] = new Point(5, 11);
    pts[2] = new Point(0, 10);
    pts[3] = new Point(1, 1);
    pts[4] = new Point(12, 3);

    Insertion.sort(pts);
    
    for (int i = 0; i < 5; i++)
        System.out.println("(" + pts[i].getX() + "," + pts[i].getY() + ")");
}}

So will sending pts in the test code make Comparable[] work as Comparable<Point>[] in the Insertion class. If so then the less() method in Insertion class will take in two Comparable<Point> arguments and uses compareTo() from the Point class. But the compareTo() inside Point class takes in Point as argument. I know we can pass Point to Comparable<Point> which is runtime polymorphism I believe. But is this what's hapening?

Moreover wanted to know is there a way to parameterize this because IntelliJ shows Raw use of parameterized class 'Comparable' warning.

  • If you are wondering how `Arrays.sort` does it look in the source code: ]https://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/be44bff34df4/src/share/classes/java/util/Arrays.java – luk2302 Jan 06 '21 at 17:04
  • Ohh no no...I'll remove that part.. – Ashwin_Iyer Jan 06 '21 at 17:07
  • 2
    Yes, there is a way to make it parametrized: `public static void sort(Comparable[] arr) { ... ` and then carry on from there. – luk2302 Jan 06 '21 at 17:10
  • Got the raw type part. But cannot make out this parameterization part. Will have to learn about it. What is this parameterization called? Never seen this type of method declaration. Anyway thank you soo much. – Ashwin_Iyer Jan 06 '21 at 17:32
  • it is called generics, they can be declared on a class / interface level, but also on a method level. – luk2302 Jan 06 '21 at 18:50

0 Answers0