开发者

Correct Type-Casting (or any other method) for a Java Generic Class

In this question What is the equivalent of the C++ Pair<L,R> in Java?, there is this sample code that I will use in my code

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 &开发者_如何学C&
                     this.second.equals(otherPair.second))) );
     }

     return false;
}

Eclipse warns me in the line "Pair otherPair = (Pair) other;" that the "Pair is a raw type. References to generic type Pair should be parameterized". I tried rewriting it to "Pair<A, B> otherPair = (Pair<A, B>) other;" but the warning is still there. How can I properly type-cast other so that no warnings will occur? Thanks!


You can use

Pair<?, ?> otherPair = (Pair<?, ?>)other;

Since equals takes an Object, you won't have any trouble. The type parameters are inconsequential in this particular code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜