daniel098:
私は、ジェネリッククラスのequals()メソッドをオーバーライドすると、私は私のジェネリック型ペアにオブジェクトをキャストしなければならないことをやりたいです。
私は「ミュート」警告に@SuppressWarnings(「未チェック」)を追加しましたが、問題はまだそこにあります。メソッドのgetType()とのgetClass()はそう)(T.getTypeを使用して、あまりにも一般的なタイプで作業していないことは問題外です。
public class Pair<T, U> {
private T first;
private U second;
public Pair(T _first, U _second)
{
first = _first;
second = _second;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
//Problem ahead!!!
Pair<T, U> other = (Pair<T, U>) obj;
...
}
}
正しく安全にそれを行うための任意の一般的な良い慣行や「トリック」がありますか?
スイーパー:
あなたはキャストすることができますobj
にPair<?, ?>
して呼び出すequals
のfirst
とsecond
:
Pair<?, ?> other = (Pair<?, ?>) obj;
return other.first.equals(first) && other.first.equals(second);
この方法では、型チェックはによって処理されますT.equals
とU.equals
、何T
とU
しています。