Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Pairs or 2-tuples in Java [duplicate]

Tags:

java

tuples

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 = ... 
like image 537
syker Avatar asked Apr 19 '10 21:04

syker


People also ask

What is a tuple pair?

A Pair is a Tuple from JavaTuples library that deals with 2 elements. Since this Pair is a generic class, it can hold any type of value in it. Since Pair is a Tuple, hence it also has all the characteristics of JavaTuples: They are Typesafe. They are Immutable.

What is Tuple2 in Java?

Technically that should be a Tuple2 , as it is a container for two heterogeneous items. Scala has tuple classes that hold anywhere between two and twenty-two items, and they're named Tuple2 through Tuple22 . To do the same thing in Java you would just implement the same pattern for Tuple2 through Tuple22 in Java.

How do you handle tuples in Java?

Note that the collection/ array must have the same type and values as the tuple. The collection/array must have the same type as the Tuple and the number of values in the collection/ array must match the Tuple class. Syntax: ClassName <type-1, type-2, …., type-n> object = ClassName.

Do pairs exist in Java?

Pairs provide a convenient way of handling simple key to value association, and are particularly useful when we want to return two values from a method. A simple implementation of a Pair is available in the core Java libraries.


1 Answers

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

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.

like image 53
maerics Avatar answered Sep 29 '22 13:09

maerics