请考虑以下代码:
public class MyClass {
public static void main(String[] args) {
Object o1 = getObject(Math.random());
Object o2 = getObject(Math.random());
if (o1.getClass().equals(o2.getClass()) { // two Cars or two Apples
Comparable c1 = (Comparable) o1;
Comparable c2 = (Comparable) o2;
int x = c1.compareTo(c2); // unsafe
System.out.println(x);
)
}
public Object getObject(double d) { // given method that may not be changed
if (d < 0.5) return (new Car()); // Car implements Comparable<Car>
else return (new Apple()); // Apple implements Comparable<Apple>
}
}
代码可以工作(给定类 Cat
和 Apple
),但编译器会警告不安全操作,因为我使用了 compareTo
而没有泛型。但是,我不知道如何解决此问题,因为我不知道如何指定 c1
和 c2
具有相同但未知的类型(在 if
子句)。有没有什么方法(当然除了使用@SuppressWarnings)来解决这个问题?
我知道这里有一个类似的问题:How to tell Java that two wildcard types are the same? 但那里给出的答案似乎是针对提问者的具体情况的。例如,它使用了我的上下文中不存在的键值映射。
最佳答案
由于条件 if (o1.getClass().equals(o2.getClass()))
保证两个对象属于同一类,
忽略该警告是安全的。你可以抑制它。
但是,由于此时它们的类型是 Object
,
将它们转换为Comparable
是不安全的。
您可以通过一些小的调整来使其更安全,使它们成为 Comparable
类:
public static void main(String[] args) {
Comparable<?> o1 = getComparable(Math.random());
Comparable<?> o2 = getComparable(Math.random());
if (o1.getClass().equals(o2.getClass())) {
// safe cast
Comparable c1 = (Comparable) o1;
Comparable c2 = (Comparable) o2;
// safe comparison
int x = c1.compareTo(c2);
System.out.println(x);
}
}
public Comparable<? extends Comparable<?>> getComparable(double d) {
if (d < 0.5) return (new Car());
return (new Apple());
}
关于java - 如何告诉编译器两个对象属于相同但未知的类(带有泛型)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47085122/