【发布时间】:2011-08-03 20:39:14
【问题描述】:
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 比看起来要难得多。有这么多\ ch 那里学习 Java 的东西,其中 99% 充其量是过时的,或者被用来对编程新手进行排名(即非常冗长),最坏的情况是彻头彻尾的垃圾……我还没有找到关于 Java 的参考资料,可以让我在上面问题的答案中很快归零。
【问题讨论】:
-
“我还没有找到一个关于 Java 的参考资料,可以让我在上面的问题的答案中快速归零。” 这可能是因为它是一个非常广泛的主题,你好像还没有开始研究。这是一个参考:The Java Tutorials > Learning the Java Language > Generics - Introduction
-
@Mark Peters:事实证明,我已经阅读了您链接的参考资料,甚至在我编写上面的代码之前,我发现它有缺陷,原因与我描述的差不多:冗长,针对编程(不仅仅是Java)新手,完全基于琐碎的示例,这些示例并未开始涵盖专业程序员每天必须处理的情况类型等。它当然没有告诉我如何解决问题在这篇文章中描述。我确信这类材料有一定的选区,但这对我没有帮助。
标签: java generics interface comparable unchecked