什么时候使用 extends 或 implements Comparable (Java) ? + 为什么我无法创建 object

when to use extends or implements Comparable (Java) ? + why I cannot create object

我正在学习数据结构,我被要求编写一个允许商店经理操纵库存的程序,使用 4 个 classes:ListInterface、ExpandableArrayList(一个 class 实现interface) , class item(存储在 Arraylist 中的类型),当然还有 Test class。

有些方法需要使用 compareTo。也就是说,Comparable,但我不知道 class 究竟应该是 Comparable? 如果我应该写 Implementsextends Comparable ?

这些是 class headers 我现在拥有的:

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>> {... } 

但出于某种原因,我无法在测试 class 中创建 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 class 到 运行 使用 class 提供的比较对 Item 类型元素的 compareTo 方法。当您从 Comparable 实现 compareTo 时,您必须提供一种比较不同项目的方法,这应该基于项目的属性 class 理想情况下。

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

这就是 class def 的样子。

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

继承tutorial

接口tutorial

应该是这样的-

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

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

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