在这个问题What is the equivalent of the C++ Pair<L,R> in Java? , 我将在我的代码中使用这个示例代码
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return
(( this.first == otherPair.first ||
( this.first != null && otherPair.first != null &&
this.first.equals(otherPair.first))) &&
( this.second == otherPair.second ||
( this.second != null && otherPair.second != null &&
this.second.equals(otherPair.second))) );
}
return false;
}
Eclipse 在“Pair otherPair = (Pair) other;”行中警告我“Pair 是原始类型。对泛型 Pair 的引用应该被参数化”。我尝试将其重写为“Pair otherPair = (Pair) other;”但警告仍然存在。我怎样才能正确地输入 other 以便不会出现警告?谢谢!
最佳答案
你可以使用
Pair<?, ?> otherPair = (Pair<?, ?>)other;
因为 equals 需要一个对象,所以你不会有任何麻烦。类型参数在此特定代码中无关紧要。
关于java - 正确的 Java 泛型类的类型转换(或任何其他方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5009883/