Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 540
John Bautista Avatar asked Apr 25 '26 05:04

John Bautista


1 Answers

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.

like image 69
Mark Peters Avatar answered Apr 27 '26 17:04

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!