英文:
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
英文:
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.
These are my headers:
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
答案1
得分: 1
如果您想要比较 AList 类的元素,您应该使用泛型类型,就像这样:AList<T extends Comparable<T>>
并对其进行边界限定。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论