Search code examples
javaarraylistdata-structurescomparecomparable

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


I am Studying Data Structures and I was asked to write a program that allows a store manager to manipulate an inventory , using 4 classes : ListInterface , ExpandableArrayList ( a class that implements the interface) , class item ( which is the type stored in the Arraylist) , and of course, a Test class.

some methods require the use of compareTo. that is , being Comparable , but I don't know what class exactly should be Comparable ? and if I should write Implements or extends Comparable ?

these are the class headers I have right now :

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

but for some reason, I cannot create an Object in the Test class. when I type:

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

I get the following errors :

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

How Can I solve this? what exactly should be changed? ..

thanks a lot in advance.


Solution

  • T which is your type Item needs to implement Comparable. This will allow the ExpandableArrayList class to run the compareTo method on elements of type Item using the comparison provided by that class. When you implement compareTo from Comparable you have to give a way for comparing different Items, this should be based on the attributes of the Item class ideally.

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

    This is what the class def would look like.

    You have to write implements for interfaces and extends for classes.

    Inheritance tutorial

    Interfaces tutorial