Using Pairs or 2-tuples in Java [duplicate]

2019-01-01 05:26发布

This question already has an answer here:

My Hashtable in Java would benefit from a value having a tuple structure. What data structure can I use in Java to do that?

Hashtable<Long, Tuple<Set<Long>,Set<Long>>> table = ...

标签: java tuples
14条回答
路过你的时光
2楼-- · 2019-01-01 05:27

javatuples is a dedicated project for tuples in Java.

Unit<A> (1 element)
Pair<A,B> (2 elements)
Triplet<A,B,C> (3 elements)
查看更多
零度萤火
3楼-- · 2019-01-01 05:30

To supplement @maerics's answer, here is the Comparable tuple:

import java.util.*;

/**
 * A tuple of two classes that implement Comparable
 */
public class ComparableTuple<X extends Comparable<? super X>, Y extends Comparable<? super Y>>
       extends Tuple<X, Y>
       implements Comparable<ComparableTuple<X, Y>>
{
  public ComparableTuple(X x, Y y) {
    super(x, y);
  }

  /**
   * Implements lexicographic order
   */
  public int compareTo(ComparableTuple<X, Y> other) {
    int d = this.x.compareTo(other.x);
    if (d == 0)
      return this.y.compareTo(other.y);
    return d;
  }
}
查看更多
大哥的爱人
4楼-- · 2019-01-01 05:31

Apache Commons provided some common java utilities including a Pair. It implements Map.Entry, Comparable and Serializable.

查看更多
旧人旧事旧时光
5楼-- · 2019-01-01 05:32

If you are looking for a built-in Java two-element tuple, try AbstractMap.SimpleEntry.

查看更多
孤独寂梦人
6楼-- · 2019-01-01 05:34
牵手、夕阳
7楼-- · 2019-01-01 05:36

Here's this exact same question elsewhere, that includes a more robust equals, hash that maerics alludes to:

http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/f8b63fc645c1b487/1d94be050cfc249b

That discussion goes on to mirror the maerics vs ColinD approaches of "should I re-use a class Tuple with an unspecific name, or make a new class with specific names each time I encounter this situation". Years ago I was in the latter camp; I've evolved into supporting the former.

查看更多
登录 后发表回答