如何在具有泛型 T 类型的情况下使用 compareTo 方法?

huangapple go评论78阅读模式
英文:

How to use compareTo method with generic T type?

问题

我有这个 UML,也许可以帮助。我在那里唯一使用的是实例变量 T[] list 和方法 f(),这个方法只是用来测试的方法。

注意:忽略 UML 中那些被覆盖的 compareto 方法,我尝试重写这个方法,但是没有成功,因为它没有在比较 t 类型。

这是我的头文件:

我有一个代表列表的类,但我不明白如何使其适用于 T 类型。

例如,在我的 Alist 类中,我有一个名为 "list" 的实例变量,它是类型为 T 的数组,我想在另一个名为 "f()" 的方法内比较这些类型为 T 的对象。

在 public static void 内部:

ListInterface<String> myList = new AList();

myList.add("a");

myList.add("b");

myList.add("c");

myList.f();

在 Alist.java 内部:

public void f() {
    System.out.println("a".compareTo("b")); //works 
    System.out.println(list[1].compareTo(list[2])); //gives the error below
}

对于第二个打印语句,我得到以下错误:

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

如何在具有泛型 T 类型的情况下使用 compareTo 方法?

如何在具有泛型 T 类型的情况下使用 compareTo 方法?

英文:

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.

如何在具有泛型 T 类型的情况下使用 compareTo 方法?

These are my headers:

如何在具有泛型 T 类型的情况下使用 compareTo 方法?

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&lt;String&gt; myList =  new AList();

myList.add(&quot;a&quot;);

myList.add(&quot;b&quot;);

myList.add(&quot;c&quot;);

myList.f();

inside Alist.java:

public void f() {

    System.out.println( &quot;a&quot;.compareTo(&quot;b&quot;)); //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 &quot;main&quot; java.lang.Error: Unresolved compilation problem: 
    The method compareTo(T) is undefined for the type T

答案1

得分: 1

如果您想要比较 AList 类的元素,您应该使用泛型类型,就像这样:AList&lt;T extends Comparable&lt;T&gt;&gt; 并对其进行边界限定

英文:

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

huangapple
  • 本文由 发表于 2020年10月25日 03:31:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64517263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定