Javaとイコールでジェネリッククラス()メソッド:型の安全性

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;

                   ...
    }
}

正しく安全にそれを行うための任意の一般的な良い慣行や「トリック」がありますか?

スイーパー:

あなたはキャストすることができますobjPair<?, ?>して呼び出すequalsfirstsecond

Pair<?, ?> other = (Pair<?, ?>) obj;
return other.first.equals(first) && other.first.equals(second);

この方法では、型チェックはによって処理されますT.equalsU.equals、何TUしています。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=167985&siteId=1