Java实现自定义Comparable接口报错:incompatible types不兼容类型
Java泛型接口使用类型不匹配问题
我在Java中使用自定义接口时遇到了类型转换报错,具体细节如下:
自定义Comparable接口
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 ) { return this.distance() < pContent.distance(); } public boolean isEqual ( Point pContent ) { return this.distance() == pContent.distance(); } public boolean isGreater ( Point pContent ) { return this.distance() > pContent.distance(); } public double distance() { return Math.sqrt( x*x + y*y ); } }
排序方法与测试代码
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)时编译器抛出如下错误:
incompatible types: Queue
cannot be converted to Queue
问题原因
Java泛型具备不变性,即使Point实现了Comparable<Point>接口,Queue<Point>和Queue<Comparable>也不存在继承关系,不能直接互相转换,因此传入Queue<Point>类型的参数到要求Queue<Comparable>的方法会触发类型不匹配报错。
解决方案
修改insortComparable方法为有界泛型方法,定义泛型参数<T extends Comparable>,适配所有实现了Comparable接口的类,同时保证输入输出类型一致:
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; }
内容的提问来源于stack exchange,提问作者codefinn
相关产品推荐
相关产品推荐

