在Java中使用对或2元组[重复]

这篇博客探讨了在Java中如何使用元组或2元组结构,以增强Hashtable的值。作者提到了一个已有的答案链接,并引用了javatuples项目以及Apache Commons提供的Pair类作为实现元组的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Using Pairs or 2-tuples in Java [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

My Hashtable in Java would benefit from a value having a tuple structure. Java中的Hashtable将受益于具有元组结构的值。 What data structure can I use in Java to do that? 我可以在Java中使用哪种数据结构来做到这一点?

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

#1楼

参考:https://stackoom.com/question/bcQm/在Java中使用对或-元组-重复


#2楼

javatuples is a dedicated project for tuples in Java. javatuples是Java 中元组的专用项目。

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

#3楼

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

#4楼

To supplement @maerics's answer, here is the Comparable tuple: 为了补充@ 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;
  }
}

#5楼

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


#6楼

Apache Commons provided some common java utilities including a Pair . Apache Commons提供了一些常见的Java实用程序,包括一 It implements Map.Entry , Comparable and Serializable . 它实现了Map.EntryComparableSerializable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值