This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Problem: Use Pairs or tuples in Java

In Java, my Hashtable uses a tuple structure. What data structures can I use in Java?

Hashtable<Long, Tuple<Set<Long>,Set<Long>>> table = ...
Copy the code

Answer a

I don’t think there is a universal tuple class in Java, but a custom tuple is as simple as this:

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; }}Copy the code

Of course, there are important properties like equality, immutability, and so on that need to be guaranteed in terms of how to design this class further, especially if you decide to use this class as a hash key.

Answer two

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

Based on the @Maerics answer, I added some useful methods:

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(a) {
        return "(" + x + "," + y + ")";
    }

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

        if(! (otherinstanceof 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(a) {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((x == null)?0 : x.hashCode());
        result = prime * result + ((y == null)?0 : y.hashCode());
        returnresult; }}Copy the code

Answer three

Apache Commons provides some common Java tools including Pair. It implements Map.Entry, Comparable, and Serializable.

Answer four

Here’s a Comparable tuple that complements @Maerics’ answer:

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);
    returnd; }}Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/2…