在 Java 中使用 Pairs 或 2-tuples

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2670982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:37:08  来源:igfitidea点击:

Using Pairs or 2-tuples in Java

javatuples

提问by syker

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

我的 Java Hashtable 将受益于具有元组结构的值。我可以在 Java 中使用什么数据结构来做到这一点?

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

采纳答案by maerics

I don't think there is a general purpose tuple class in Java but a custom one might be as easy as the following:

我认为 Java 中没有通用的元组类,但自定义的元组类可能如下所示:

public class Tuple<X, Y> { 
  public final X x; 
  public final Y y; 
  public Tuple(X x, Y y) { 
    this.x = x; 
    this.y = y; 
  } 
} 

Of course, there are some important implications of how to design this class further regarding equality, immutability, etc., especially if you plan to use instances as keys for hashing.

当然,如何在相等性、不变性等方面进一步设计这个类有一些重要的含义,特别是如果你打算使用实例作为散列的键。

回答by ColinD

Create a class that describes the concept you're actually modeling and use that. It can just store two Set<Long>and provide accessors for them, but it should be named to indicate what exactly each of those sets is and why they're grouped together.

创建一个类来描述您实际建模的概念并使用它。它可以只存储两个Set<Long>并为它们提供访问器,但它应该被命名以表明这些集合中的每一个究竟是什么以及它们为什么被分组在一起。

回答by not-just-yeti

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

这是其他地方的完全相同的问题,其中包括一个更强大的equalshashmaerics 暗示:

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

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.

该讨论继续反映 maerics 与 ColinD 的方法“我是否应该重新使用具有不特定名称的类元组,或者每次遇到这种情况时都使用特定名称创建一个新类”。多年前,我在后者阵营;我已经演变成支持前者。

回答by Daniel

javatuplesis a dedicated project for tuples in Java.

javatuples是 Java中元组的专用项目。

Unit<A> (1 element)
Pair<A,B> (2 elements)
Triplet<A,B,C> (3 elements)

回答by Aram Kocharyan

As an extension to @maerics nice answer, I've added a few useful methods:

作为@maerics 不错答案的扩展,我添加了一些有用的方法:

public class Tuple<X, Y> { 
    public final X x; 
    public final Y y; 
    public Tuple(X x, Y y) { 
        this.x = x; 
        this.y = y; 
    }

    @Override
    public String toString() {
        return "(" + x + "," + y + ")";
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }

        if (!(other instanceof Tuple)){
            return false;
        }

        Tuple<X,Y> other_ = (Tuple<X,Y>) other;

        // this may cause NPE if nulls are valid values for x or y. The logic may be improved to handle nulls properly, if needed.
        return other_.x.equals(this.x) && other_.y.equals(this.y);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((x == null) ? 0 : x.hashCode());
        result = prime * result + ((y == null) ? 0 : y.hashCode());
        return result;
    }
}

回答by Alexei Averchenko

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

为了补充@maerics 的回答,这里是Comparable元组:

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;
  }
}

回答by at7000ft

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

如果您正在寻找内置的 Java 两元素元组,请尝试AbstractMap.SimpleEntry.

回答by rhgb

Apache Commonsprovided some common java utilities including a Pair. It implements Map.Entry, Comparableand Serializable.

Apache Commons提供了一些常见的 Java 实用程序,包括Pair。它实现Map.Entry,ComparableSerializable

回答by see2851

Android Tuple Utils

Android 元组实用程序

This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.

该对象提供了一个合理的 equals() 实现,如果 equals() 在每个包含的对象上为真,则返回真。

回答by Ste

You can use Google Guava Table

你可以使用谷歌番石榴表