我有这两个类,其中一个是具有泛型类型的sortedLinkedList
的{{1}}类。当我在main中实现它们时:
Comparable
它会显示此错误:
Test.java:12:错误:类型参数公寓不在范围内 类型变量T SortedListInterface aptList = new SortedLinkedList(); ^其中T是一个类型变量: T扩展在接口SortedListInterface
中声明的Comparable
SortedListInterface<Apartment> aptList=new SortedLinkedList<Apartment>();
上课:
Apartment
/**A class that holds Apartment informations*/
public class Apartment{
private String id;
private int yearsLeft;
//class methods
}//end Apartment class
上课:
SortedLinkedList
这个想法是我想根据他们的年份(/**
* A class that implements the ADT sorted list by using a chain of nodes.
* Duplicate entries are allowed.
*
* @author Frank M. Carrano
* @version 2.0
*/
public class SortedLinkedList<T extends Comparable<? super T>>
implements SortedListInterface<T>
{
//class methods
} // end SortedLinkedList
)对所有公寓进行排序,但我是int yearsLeft
课程的新手,所以我不知道如何可能会与它合作。
我的问题是:如何修复错误?如果可能的解释。
答案 0 :(得分:0)
您将SortedLinkedList
定义为SortedLinkedList <T extends Comparable<? super T>>
这意味着T(您的appartement类)必须是扩展Comparable<? super T>
你的appartement课程没有扩展Comparable
答案 1 :(得分:0)
能够将Apartment
与SortedLinkedList
一起使用,
它需要实现Comparable
接口,例如:
class Apartment implements Comparable<Apartment> {
@Override
public int compareTo(Apartment o) {
return 0;
}
// ... the rest of your code
}
您想如何订购公寓?
您需要相应地实现compareTo
方法。
如果您想通过yearsLeft
订购公寓,可以将其写为:
@Override
public int compareTo(Apartment o) {
return Integer.compare(yearsLeft, o.yearsLeft);
}
要按相反的顺序按yearsLeft
排序,您可以将其写为:
@Override
public int compareTo(Apartment o) {
return -Integer.compare(yearsLeft, o.yearsLeft);
}
您可以在JavaDoc中了解有关Comparable
界面的更多信息。
答案 2 :(得分:0)
只需将类SortedLinkedList
定义为具有条件类型参数T extends Comparable<? super T>
的泛型类。
因此,在实例化中,您传递的类型参数必须满足。
但你的班级Apartment
并不满足。
只需让课程Apartment
实现Comparable<Apartment>