java - 无法理解没有类型参数的泛型接口的使用
问题描述
这是我正在实现的排序类的代码。
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
作为参数。我知道我们可以传递Point
给Comparable<Point>
我相信的运行时多态性。但这就是正在发生的事情吗?
此外想知道有没有办法参数化它,因为 IntelliJ 显示Raw use of parameterized class 'Comparable'
警告。
解决方案
推荐阅读
- python - 使用列表中的 \n 连接列表中的字符串(Python)
- c - 为什么运行时会出现分段错误?它作为 TCP 客户端-服务器工作,并且在客户端的用户 ID 输入处发生分段错误
- php - POST ajax json 对 PHP 的响应
- javascript - JavaScript - 如何从 CSV 文件构建层次结构对象
- python - 正确使用 post_save 信号?
- java - 使用 @Embeddable 类的 save() 方法时出现“提供了错误类型的 id”错误
- r - 有没有一种简单的方法可以在 rmarkdown/bookdown 中使用符号作为脚注?
- python - 使用 yfinance 获取错误的交易量
- c++ - 空的 SDL2 窗口需要大量 (40%+) GPU 渲染?
- sql-server - XML 文件 SSIS 到 SQL Server = 从列中的十进制值中删除尾随 0