gpt4 book ai didi

Java:删除 "Comparable is a raw type"警告

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:21 27 4
gpt4 key购买 nike

假设我有一个名为 foo 的方法,将 2 个对象作为参数。这两个对象属于同一类型,并且都实现了可比较的接口(interface)。

void foo(Object first, Object second){

if (!first.getClass().isInstance(second)) //first and second of the same type
return;

Comparable firstComparable = (Comparable)first; //WARNING
Comparable secondComparable = (Comparable)second; //WARNING

int diff = firstComparable.compareTo(secondComparable); //WARNING
}

前两个警告是:

Comparable is a raw type. References to generic type Comparable should be parameterized

最后的警告:

Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable should be parameterized

我如何重构我的代码以移除这些警告?

编辑:我可以在不更改 foo 方法签名的情况下这样做吗?

最佳答案

你必须告诉编译器它们是同一类型并且具有可比性。如果您无法更改签名,则可以添加一种方法以实现向后兼容性。

@SuppressWarnings("unchecked")
static void foo(Object first, Object second) {
foo((Comparable) first, (Comparable) second);
}

static <T extends Comparable<T>> void foo(T first, T second){
int diff = first.compareTo(second); // no warning.
}

关于Java:删除 "Comparable is a raw type"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7008623/

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