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.