首页 > 解决方案 > 无法理解没有类型参数的泛型接口的使用

问题描述

这是我正在实现的排序类的代码。

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;
}}

在这里,我无法理解在没有类型参数的情况下如何使用可比较的接口。

假设我想传递一个实现 Comparable 的类 Point。这里是

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);
}}

这是我正在测试的测试代码

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() + ")");
}}

发送pts测试代码也会Comparable[]Comparable<Point>[]Insertion课堂上一样工作。如果是这样,那么less()Insertion 类中的方法将接受两个Comparable<Point>参数并compareTo()Point类中使用。但是compareTo()内部的 Point 类Point作为参数。我知道我们可以传递PointComparable<Point>我相信的运行时多态性。但这就是正在发生的事情吗?

此外想知道有没有办法参数化它,因为 IntelliJ 显示Raw use of parameterized class 'Comparable' 警告。

标签: javagenericsinterfacecomparable

解决方案


推荐阅读