juan
juan

Reputation: 113

How to use compareTo method with generic T type?

I got this UML, maybe it helps. The only thing I'm using there is the instance variable T[] list and the method f() which is method just for testing.

(edited)note: Ignore those overrided compareto methods in the UML, I tried to override the method but it didnt work because it was not comparing the t types.

enter image description here

These are my headers:

enter image description here

I have a class that represents a list, but I do not understand how to make it work with T types. For example in my class Alist I have an instance variable called "list" which is a array of type T, I would like to compare this Type T objects inside another method called "f()" .

inside public static void:

ListInterface<String> myList =  new AList();

myList.add("a");

myList.add("b");

myList.add("c");

myList.f();

inside Alist.java:

public void f() {

    System.out.println( "a".compareTo("b")); //works 

    System.out.println(list[1].compareTo(list[2]));  //gives the error below

}

For the second print statement I get the error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method compareTo(T) is undefined for the type T

Upvotes: 0

Views: 847

Answers (1)

badger
badger

Reputation: 3246

if you want to compare the elements of AList class you should use your generics type like this AList<T extends Comparable<T>> and bound it.

Upvotes: 1

Related Questions