gpt4 book ai didi

Java:未经检查的调用 compareTo(T)

转载 作者:搜寻专家 更新时间:2023-11-01 01:08:50 27 4
gpt4 key购买 nike

 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 的引用资料我很快就把上面问题的答案归零了。

最佳答案

您应该使用通用参数声明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));
}
}

关于Java:未经检查的调用 compareTo(T),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6932996/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com