我正在研究数据结构,被要求编写一个程序,该程序允许商店经理使用以下四个类来处理库存:ListInterface,ExpandableArrayList(实现接口的类),类项目(存储在Arraylist中的类型) ),当然还有Test类。

有些方法需要使用compareTo。就是说,是可比的,但是我不知道什么班级应该是可比的?
以及我应该编写Implements还是扩展Comparable?

这些是我现在拥有的类头文件:

public interface ListInterface<T extends Comparable <?super T >> {... }

public class ExpandableArrayList <T extends Comparable <? super T >>
implements ListInterface <T> { ...... }

public class Item<T extends Comparable<T>> {... }


但是由于某种原因,我无法在Test类中创建Object。
当我键入:

ListInterface<Item> inventoryList= new ExpandableArrayList<Item>();


我收到以下错误:

Test.java:9: error: type argument Item is not within bounds of type-variable T
ListInterface<Item> inventoryList= new ExpandableArrayList<Item> () ;
where T is a type-variable:
T extends Comparable<? super T> declared in interface ListInterface


Test.java:9: error: type argument Item is not within bounds of type-variable T
ListInterface<Item> inventoryList= new ExpandableArrayList<Item> () ;
where T is a type-variable:
T extends Comparable<? super T> declared in class ExpandableArrayList


我该如何解决?究竟应该更改什么? ..

非常感谢。

最佳答案

T是您的Item类型,需要实现Comparable。这将允许ExpandableArrayList类使用该类提供的比较在Item类型的元素上运行compareTo方法。当从Comparable实现compareTo时,必须提供一种比较不同Item的方法,这应该理想地基于Item类的属性。

public class Item implements Comparable<Item> {... }


这就是类def的外观。

您必须为接口编写implements,为类编写extends

继承tutorial

接口tutorial

关于java - 什么时候使用扩展或实现Comparable(Java)? +为什么我不能创建对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29216961/

10-13 07:57
查看更多