kjo*_*kjo 4 java generics interface unchecked comparable
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 }
Run Code Online (Sandbox Code Playgroud)
编译上面的代码会产生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
Run Code Online (Sandbox Code Playgroud)
我尝试了更多的变种,但警告仍然存在.编写和调用上面的test.compare方法的正确方法是什么?
谢谢!
PS:test.compare只是一个例子; 我不需要这样的功能; 但我需要实现一个函数,就像test.compare一样,需要在其签名中包含Comparable实现对象.
PS2:我已经编程了25年以上,我甚至在大约10年前编写了Java一段时间,但现在使用Java(我的工作需要)让我疯狂.对于有经验的程序员来说,学习Java比看起来要困难得多.在那里学习Java有很多东西,其中99%最好是过时的,或者倾向于对编程新手进行排名(即大量冗长),最糟糕的是直接垃圾...我还没有找到关于Java将让我快速回答上述问题的答案.
您应该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));
}
}
Run Code Online (Sandbox Code Playgroud)