java泛型中的通配符

时间:2013-01-12 18:29:33

标签: java

我获得了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;
    }

}

我不了解实施情况。我需要一个解释。

1 个答案:

答案 0 :(得分: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值,并返回一个新对,其中包含对a的两个引用。

你不能简单地这样做

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

因为您必须返回Pair<A, A>。您获得Pair<A, ?>作为参数,因此您只能确定给定对的第一个值是A类型。您不知道pair.b的类型。

相关问题