我收到编译警告:"ExampleConsumer.java使用未经检查或不安全的操作return example.distance(other);
。如何正确检查类型?显然,我需要强制要求类型相同。
这是我的代码:
示例.java
public abstract class Example<T, U> {
public T t;
public U u;
public Example(T t, U u) {
this.t = t;
this.u = u;
}
abstract double distance(Example<T, U> other);
}
特殊例子.java
public class SpecialExample extends Example<Integer, Double> {
public SpecialExample(Integer i, Double d) {
super(i, d);
}
@Override
double distance(Example<Integer, Double> other) {
return (double)(t - other.t) + u * other.u;
}
}
不好的例子.java
public class BadExample extends Example<String, String> {
public BadExample(String s1, String s2) {
super(s1, s2);
}
@Override
double distance(Example<String, String> other) {
return (double)(t.length() + other.t.length()) + (u.length() * other.u.length());
}
}
示例消费者.java
public class ExampleConsumer<E extends Example> {
private E example;
public ExampleConsumer(E example) {
this.example = example;
}
public double combine(E other) {
return example.distance(other);
}
}
主.java
class Main {
public static void main(String[] args) {
SpecialExample special = new SpecialExample(1, 2.0);
ExampleConsumer<SpecialExample> consumer = new ExampleConsumer<>(special);
BadExample bad = new BadExample("foo", "bar");
consumer.combine(special); // compiles with warning
// consumer.combine(bad); // doesn't compile = good!
}
}
这是一个解决方案:
示例消费者.java
public class ExampleConsumer<A, B, E extends Example<A, B>> {
private E example;
public ExampleConsumer(E example) {
this.example = example;
}
public double combine(E other) {
return example.distance(other);
}
}
主.java
class Main {
public static void main(String[] args) {
// ...
ExampleConsumer<Integer, Double, SpecialExample> consumer = new ExampleConsumer<>(special);
// ...
}
}
但我宁愿不必在 Main 中重复双精度/整数类型.java :/