【发布时间】:2021-10-20 10:21:33
【问题描述】:
我的 Java 接口有问题。
界面:
public interface Comparable<ContentType> {
public boolean isGreater ( ContentType pContent );
public boolean isEqual ( ContentType pContent );
public boolean isLess ( ContentType pContent );
}
实现接口的类“Point”:
public class Point implements Comparable<Point>{
private double x;
private double y;
public Point ( double pX, double pY ) {
x = pX;
y = pY;
}
public boolean isLess ( Point pContent ) {
if ( this.distance() < pContent.distance() ) {
return true;
} else {
return false;
}
}
public boolean isEqual ( Point pContent ) {
if ( this.distance() == pContent.distance() ) {
return true;
} else {
return false;
}
}
public boolean isGreater ( Point pContent ) {
if ( this.distance() > pContent.distance() ) {
return true;
} else {
return false;
}
}
public double distance() {
return Math.sqrt( x*x + y*y );
}
}
“算法”类有一个用于接口 Comparable 的排序方法并测试这个排序方法:
public class Algorithms {
public static List<Comparable> insortComparable( Queue<Comparable> pQueue ) {
List<Comparable> l = new List<Comparable>();
while ( !pQueue.isEmpty() ) {
if ( l.isEmpty() ) {
l.append(pQueue.front());
pQueue.dequeue();
} else {
l.toFirst();
while (l.hasAccess() && pQueue.front().isGreater(l.getContent())) {
l.next();
}
if ( l.hasAccess() ) {
l.insert(pQueue.front());
} else {
l.append(pQueue.front());
}
pQueue.dequeue();
}
}
return l;
}
public static Queue<Point> randomQueuePoint() {
Queue<Point> q = new Queue<Point>();
for ( int i = 0; i < 10; i++ ) {
q.enqueue( new Point( Math.random()*100, Math.random()) );
}
return q;
}
public void test() {
Queue<Point> q = randomQueuePoint();
List<Point> l = insortComparable(q);
}
}
在测试方法中,我调用方法insortComparable(q),但编译器在q下划线,编译器说:
不兼容的类型:Queue
无法转换为 Queue
问题出在哪里?
更新:
我发现了我的错误,我想给你一个更新,所以有同样问题的人可以得到一些帮助。
有人会说:
public static <T extends Comparable> List<T> insortComparable( Queue<T> pQueue ) {
List<T> l = new List<T>();
while ( !pQueue.isEmpty() ) {
if ( l.isEmpty() ) {
l.append(pQueue.front());
pQueue.dequeue();
} else {
l.toFirst();
while (l.hasAccess() && pQueue.front().isGreater(l.getContent())) {
l.next();
}
if ( l.hasAccess() ) {
l.insert(pQueue.front());
} else {
l.append(pQueue.front());
}
pQueue.dequeue();
}
}
return l;
}
【问题讨论】:
-
虽然
Point"is-a"Comparable,Queue<Point>不是Queue<Comparable>。您需要添加协方差关键字才能完成这项工作。
标签: java generics interface compiler-errors