java - 正确的 Java 泛型类的类型转换(或任何其他方法)

标签 java generics casting

在这个问题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/

相关文章:

java - Spring Boot JSON 返回有时返回空字符串有时返回 null 关键字

java - LambdaConversionException 与泛型 : JVM bug?

c# - 不允许重载泛型类型参数?

iphone - 如何从 as 和 id 传入的整数获取 NSDate?

c++ - C/C++ 中的类型转换到底是什么?

java - 为什么在整数的情况下不需要显式转换?

java - 在Java中用零填充

java - 无法解析 com.android.tools.build :gradle:3. 1.4,react-native run-android

Java 使列表线程的副本安全吗?

c# - 将泛型类型的实例返回到在运行时解析的函数