16

只是尝试我在过去的试卷中找到的这个问题,以便我可以为即将到来的 Java 考试做准备。

提供一个通用类 Pair 来表示成对的事物。该类应提供构造函数、获取对的第一个成员的方法、获取对的第二个成员的方法、设置对的第一个成员的方法、设置对的第二个成员的方法. 该类应该在两种类型上进行参数化,一种用于第一个成员,另一种用于该对的第二个成员。

这是这个问题的正确实现吗?

public class Pair<firstThing, secondThing>{
   private firstThing first;//first member of pair
   private secondThing second;//second member of pair

   public Pair(firstThing first, secondThing second){
     this.first = first;
     this.second = second;
   }

   public void setFirst(firstThing first){
    this.first = first;
   }

   public void setSecond(secondThing second) {
     this.second = second;
   }

   public thing getFirst() {
     return this.first;
   }

   public thing getSecond() {
     return this.second;
   }
}
4

15 回答 15

23

几乎。我会这样写:

public class Pair<F, S> {
    private F first; //first member of pair
    private S second; //second member of pair

    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    public void setFirst(F first) {
        this.first = first;
    }

    public void setSecond(S second) {
        this.second = second;
    }

    public F getFirst() {
        return first;
    }

    public S getSecond() {
        return second;
    }
}

编辑:我同意@karmakaze 的评论。代码应该跳过设置器并设置第一个和第二个 final 以保持它不可变。

于 2011-05-18T13:04:57.710 回答
11

对 Pair 类的需求通常出现在较大的项目中——我即将(重新)为当前项目实现一个(因为以前的实现无法访问)。

通常,我将其设为不可变 POJO,并具有创建实例的便利功能。例如:

public class Pair<T,U>
{
    public final T first;
    public final U second;
    public static <T,U> Pair<T,U> of(T first, U second);
}

以便最终用户可以编写:

return Pair.of (a, b);

Pair<A,B> p = someThing ();
doSomething (p.first);
doSomethingElse (p.second);

如上所述,Pair 类还应该实现 hashCode()、equals()、可选但有用的 toString(),以及可能的 clone() 和 compareTo(),以便在 T 和 U 支持的情况下使用——尽管需要额外的工作需要描述 Pair 类如何支持这些合约。

于 2013-09-23T12:11:49.437 回答
5

这是来自 Android SDK 的实现

/**
 * Container to ease passing around a tuple of two objects. This object provides a sensible
 * implementation of equals(), returning true if equals() is true on each of the contained
 * objects.
 */
public class Pair<F, S> {
    public final F first;
    public final S second;

    /**
     * Constructor for a Pair.
     *
     * @param first the first object in the Pair
     * @param second the second object in the pair
     */
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    /**
     * Checks the two objects for equality by delegating to their respective
     * {@link Object#equals(Object)} methods.
     *
     * @param o the {@link Pair} to which this one is to be checked for equality
     * @return true if the underlying objects of the Pair are both considered
     *         equal
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equal(p.first, first) && Objects.equal(p.second, second);
    }

    /**
     * Compute a hash code using the hash codes of the underlying objects
     *
     * @return a hashcode of the Pair
     */
    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
    }

    /**
     * Convenience method for creating an appropriately typed pair.
     * @param a the first object in the Pair
     * @param b the second object in the pair
     * @return a Pair that is templatized with the types of a and b
     */
    public static <A, B> Pair <A, B> create(A a, B b) {
        return new Pair<A, B>(a, b);
    }
}
于 2013-09-03T07:43:01.373 回答
3

我认为没有。 引用:

“该类应该在两种类型上进行参数化......”

我认为他们期望:

public class Pair<ThingA, ThingB>
于 2011-05-18T12:54:16.373 回答
2

通常一个泛型 Pair 类型有两个泛型类型参数,而不是一个 - 所以你可以有(比如说) a Pair<String, Integer>。这通常更有用,IMO。

我还建议您为类型参数考虑一个比“事物”更传统的名称。例如,您可以使用Pair<A, B>or Pair<T, U>

于 2011-05-18T12:54:22.520 回答
2

吸气剂坏了

public thing getFirst() {
  return thing.first;
}

public thing getSecond() {
  return thing.second;
}

thing应该替换为this

于 2011-05-18T12:56:34.227 回答
2

编辑后,看起来不错。

但是,您确实应该实现hashCodeandequals方法,以便包含相同对象的两个对将彼此相等,并且可以用作 HashMap 中的键。如果toString你感觉很慷慨。这些方法不需要满足您的要求,但它们是优秀程序员会添加的东西。

于 2011-05-18T13:26:27.233 回答
1

该类应该在两种类型上进行参数化,一种用于第一个成员,另一种用于该对的第二个成员。

你只有一个参数。

你需要类似的东西,Pair<F,S>并使用 Fthing用于第一个和 Sthing用于第二个。

于 2011-05-18T12:55:41.080 回答
1

否。您是否尝试过对其进行编码以查看它是否有效?

您似乎错过了这部分要求:

该类应该在两种类型上进行参数化,一种用于第一个成员,另一种用于该对的第二个成员。

这意味着该类可能应该被定义为更像:

public class Pair<T1, T2>

其他方法也相应更新。(顺便说一句,我使用 T1 和 T2 来指代类型,因为按照惯例,使用的是短的 - 1 或 2 字符 - 标识符)。

还,

return thing.first;

return thing.second;

不会工作,就像在你的例子中一样,thing是一种类型,而不是一个对象。想想你想在这里返回什么。你甚至需要调用一个方法吗?

进行更改后,对其进行编码并编写单元测试或简单的测试工具来检查它是否有效。

于 2011-05-18T13:00:45.540 回答
1

Apache Commons Lang 有一个通用的对实现

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

于 2018-02-27T13:09:55.260 回答
0

thing是一个非常规符号的类型变量- 我们通常使用一个大写的后者(如T)。然后:类型变量没有任何方法,因此您的 getter 不会编译。

快速改进:全部替换thingT

快速修复吸气剂:

public T getFirst() {
 return first;
}

public T getSecond() {
 return second;
}

一项要求是允许配对成员使用两种不同的类型。所以类签名应该是这样的:

public Pair<S,T> {
  private S first;
  private T second;
  //...
}
于 2011-05-18T12:55:28.630 回答
0

我的配对版本。这也处理比较。PS:大部分代码取自AOSP。

package util;

import java.util.Objects;

public class Pair<F extends Comparable<F>, S extends Comparable<S>>
  implements Comparable<Pair<F, S>> {

    public final F first;
    public final S second;

    /**
     * Constructor for a Pair.
     *
     * @param first  the first object in the Pair
     * @param second the second object in the pair
     */
    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    /**
     * Checks the two objects for equality by delegating to their respective
     * {@link Object#equals(Object)} methods.
     *
     * @param o the {@link Pair} to which this one is to be checked for equality
     * @return true if the underlying objects of the Pair are both considered
     * equal
     */
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
    }

    /**
     * Compute a hash code using the hash codes of the underlying objects
     *
     * @return a hashcode of the Pair
     */
    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
    }

    /**
     * Convenience method for creating an appropriately typed pair.
     *
     * @param a the first object in the Pair
     * @param b the second object in the pair
     * @return a Pair that is templatized with the types of a and b
     */
    public static <A extends Comparable<A>, B extends Comparable<B>> Pair<A, B> create(A a, B b) {
        return new Pair<>(a, b);
    }

    @Override
    public int compareTo(Pair<F, S> that) {
        int cmp = this.first.compareTo(that.first);
        if (cmp == 0)
            cmp = this.second.compareTo(that.second);
        return cmp;
    }
}
于 2016-03-02T14:11:04.440 回答
0

我实现了类似的东西,但使用静态构建器和链式设置器

public class Pair<R, L> {

private R left;
private L right;

public static <K,V> Pair<K, V> of(K k, V v) {
    return new Pair<K,V>(k, v);
}

public Pair() {}

public Pair(R key, L value) {
    this.left(key);
    this.right(value);
}

public R left() {
    return left;
}

public Pair<R, L> left(R key) {
    this.left = key;
    return this;
}

public L right() {
    return right;
}

public Pair<R, L> right(L value) {
    this.right = value;
    return this;
}
}
于 2017-01-28T12:17:50.033 回答
0

创建 Generic Pair 类需要很多时间。使用SimpleEntry会容易得多。

static class Pair {
    public static <T, U> Map.Entry<T, U> of(T first, U second) {
        return new AbstractMap.SimpleEntry<>(first, second);
    }
}
于 2021-09-23T16:04:56.803 回答