在Java里面使用Pairs或者二元组

这篇博客探讨了在Java中如何使用Pairs或二元组。由于Java没有内置的元组类,作者提到了使用自定义元组、扩展已有类以及Apache Commons的Pair类作为替代方案。各回答详细阐述了不同实现方式及其特点。

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

问题:在Java里面使用Pairs或者二元组

在Java里面,我的Hashtable要用到一个元组结构。在Java里面,我可以使用的什么数据结构呢?

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

回答一

我不认为在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; 
  } 
} 

当然,关于如何进一步设计这个类,我们还要保证一些重要的性质,如相等性、不变性等,特别是对于如果你决定使用这个类作为hash的key的话。

回答二

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

回答三

Apache Commons提供了一些常用的Java工具包括Pair。它实现了Map.Entry, Comparable 和 Serializable.

回答四

下面是一个Comparable元组,补充了@maerics的答案:

import java.util.*;

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


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

文章翻译自Stack Overflow:https://stackoverflow.com/questions/2670982/using-pairs-or-2-tuples-in-java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值