简体   繁体   中英

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 &&
                     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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM