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 = ...
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With