1 class test {
2 public static int compare0(Comparable x, Comparable y) {
3 return x.compareTo(y);
4 }
5 public static int compare1(Object x, Object y) {
6 return ((Comparable) x).compareTo((Comparable) y);
7 }
8 public static int compare2(Object x, Object y) {
9 Comparable p = (Comparable) x;
10 Comparable q = (Comparable) y;
11 return (p).compareTo(q);
12 }
13 public static void main(String[] args) {
14 Comparable zero = new Integer(0);
15 Comparable one = new Integer(1);
16 int c = (zero).compareTo(one);
17 }
18 }
编译上面的代码会产生4个警告:
% javac -Xlint:unchecked test.java
test.java:3: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable
return x.compareTo(y);
^
test.java:7: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable
return ((Comparable) x).compareTo((Comparable) y);
^
test.java:13: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable
return (p).compareTo(q);
^
test.java:19: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable
int c = (zero).compareTo(one);
^
4 warnings
我尝试了更多变种,但警告仍然存在。编写和调用上面的test.compare方法的正确方法是什么?
谢谢!
PS:test.compare只是一个例子;我不需要这样的功能;但我需要实现一个函数,就像test.compare一样,需要在其签名中包含可比较的实现对象。
PS2:我已经编程了25年以上,我甚至在大约10年前编写了Java一段时间,但现在使用Java(我的工作需要)让我疯狂。对于有经验的程序员来说,学习Java比看起来要困难得多。有这么多 在那里学习Java的东西,其中99%最好是过时的,或者倾向于对编程新手进行排名(即大量冗长),最糟糕的是直接垃圾......我还没有找到关于Java的参考资料在上述问题的答案中,我很快就归零了。答案 0 :(得分:6)
Comparable
是通用的 - 您应该使用Comparable<Integer>
答案 1 :(得分:6)
您应该使用泛型参数声明compare
方法。
public class ThisTest
{
public static <T extends Comparable<T>> int compare(T x, T y) {
if (x == null)
return -(y.compareTo(x));
return x.compareTo(y);
}
public static void main()
{
// Type inferred
int c = compare(Integer.valueOf(0), Integer.valueOf(1));
// Explicit generic type parameter
c = ThisTest.<Integer>compare(Integer.valueOf(0), Integer.valueOf(1));
}
}
答案 2 :(得分:2)
真正的问题是你试图在静态方法中进行比较。使进行比较的方法非静态,实例化一个或多个“tester”对象并为每个对象提交一个类型。例如:
test<String> strTester = new test<String>();
然后调用String对象的比较方法:
int retCode = strTester.comp(a, b)
如果要比较其他类型的对象(如整数),则需要一个新的测试对象,如:
test<Integer> intTester = new test<Integer>();
如果您愿意这样做,那么您的课程可以按照以下方式定义:
class test<T extends Comparable<T>> {
public int comp(T x, T y) {
...
}
}
答案 3 :(得分:1)
将zero
和one
声明为Integer
或Comparable<Integer>
而非原始类型。
Angelika Langer制作了a great reference for generics.它是一个分层的常见问题解答,可以让您快速找到大多数通用类型问题的具体答案。在这种情况下,您可能会发现section on raw types有用。