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,需要在其签名中包含 Comparable 实现对象。
PS2:我已经编程了 25 多年,我什至在大约 10 年前编写了一段时间的 Java,但是现在使用 Java(我的工作需要)让我发疯。对于有经验的程序员来说,学习 Java 比看起来要难得多。那里有很多关于学习 Java 的东西,其中 99% 充其量是过时的,或者是为了给编程新手排名(即非常冗长),最坏的情况是彻头彻尾的垃圾……我还没有找到关于Java 将让我在上述问题的答案中快速归零。