This question already has an answer here:
- A Java collection of value pairs? (tuples?) 17 answers
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 = ...
I will start from a general point of view about tuples in Java and finish with an implication for your concrete problem.
1) The way tuples are used in non-generic languages is avoided in Java because they are not type-safe (e.g. in Python:
tuple = (4, 7.9, 'python')
). If you still want to use something like a general purpose tuple (which is not recommended), you should useObject[]
orList<Object>
and cast the elements after a check withinstanceof
to assure type-safety.Usually, tuples in a certain setting are always used the same way with containing the same structure. In Java, you have to define this structure explicitly in a
class
to provide well-defined, type-safe values and methods. This seems annoying and unnecessairy at first but prevents errors already at compile-time.2) If you need a tuple containing the same (super-)classes
Foo
, useFoo[]
,List<Foo>
, orList<? extends Foo>
(or the lists's immutable counterparts). Since a tuple is not of a defined length, this solution is equivalent.3) In your case, you seem to need a
Pair
(i.e. a tuple of well-defined length 2). This renders maerics's answer or one of the supplementary answers the most efficient since you can reuse the code in the future.Android Tuple Utils
This object provides a sensible implementation of equals(), returning true if equals() is true on each of the contained objects.
I don't think there is a general purpose tuple class in Java but a custom one might be as easy as the following:
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.
Another 2 cents : Starting with Java 7, there is now a class for this in standard Lib : javafx.util.Pair.
And Yes, It is standard Java, now that JavaFx is included in the JDK :)
Create a class that describes the concept you're actually modeling and use that. It can just store two
Set<Long>
and provide accessors for them, but it should be named to indicate what exactly each of those sets is and why they're grouped together.Though the article is pretty old now, and though I understand that I'm not really very helpful, I think the work done here: http://www.pds.ewi.tudelft.nl/pubs/papers/cpe2005.pdf, would have been nice in mainstream Java.
You can do things like:
or
or
Here tuples are:
This approach increases