-4

Pair.java クラスが与えられ、PairTools.java クラスを実装する必要があります。

Pair.java

import java.util.Objects;

public class Pair<A, B> {

    public final A a;
    public final B b;

    public Pair(A a, B b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public String toString() {
        // appending things to the empty string prevents us from having to worry about null
        // and calling toString explicitly, Objects.toString(a) + " " + Objects.toString(b)
        // would also work
        return "" + a + " " + b;
    }

    @Override
    public boolean equals(Object obj) {
        // `obj instanceof Pair` will automatically return false if obj is null
        if (!(obj instanceof Pair)) {
            return false;
        }

        // some warnings with generics are unavoidable
        @SuppressWarnings("unchecked")
        Pair<A, B> p = (Pair<A, B>) obj;

        // we use Objects.equals() to handle nulls easily
        return Objects.equals(a, p.a) && Objects.equals(b, p.b);
    }

    @Override
    public int hashCode() {
        // we use Objects.hashCode() to handle nulls easily, 
        // the operation ^ is XOR, not exponentiation
        return Objects.hashCode(a) ^ Objects.hashCode(b);
    }
}

PairTools.java では、次のメソッドを実装する必要があります。

public class PairTools {

    /**
     * this is how you can use wildcards in generics
     * 
     * @param pair (assume never null)
     * @return a pair containing two references to a of the given pair
     */
    public static <A> Pair<A, A> copyA(Pair<A, ?> pair) {
        return null;
    }

}

実装がわかりません。説明が必要です。

4

1 に答える 1

0

可能な実装は次のようになります。

public class PairTools {

    /**
     * this is how you can use wildcards in generics
     * 
     * @param pair (assume never null)
     * @return a pair containing two references to a of the given pair
     */
    public static <A> Pair<A, A> copyA(Pair<A, ?> pair) {
        return new Pair<A, A>(pair.a, pair.a);
    }

}

これは、指定されたペアの値を無視し、bへの 2 つの参照を持つ新しいペアを返しますa

これを単純に行うことはできません

return new Pair<A, A>(pair.a, pair.b);

を返す必要があるためですPair<A, A>。as パラメーターを取得するPair<A, ?>ため、指定されたペアの最初の値が type であることのみを確認できますA。の型がわかりませんpair.b

于 2013-01-12T18:35:52.217 に答える