Simplist way to create a tuple in java?
14,191
Solution 1
This is as simple as it gets:
public class Pair<S, T> {
public final S x;
public final T y;
public Pair(S x, T y) {
this.x = x;
this.y = y;
}
}
Solution 2
Yes. Best practices would be to make the fields private and provide getters for them.
For many people (including [most of?] the language designers), the idea of a tuple runs counter to the strong typing philosophy of Java. Rather than just a tuple, they would prefer a use-case-specific class, and if that class only has two getters and no other methods, so be it.
Author by
omega
Updated on June 18, 2022Comments
-
omega almost 2 years
Is there a simple way to create a 2 element tuple in java? I'm thinking of making a class and declaring the variables as final. Would this work?
-
yshavit about 11 yearsIterable likely isn't appropriate.
Iterable<T>
is for something with some number of elements, all of typeT
. A tuple is, in general, a heterogeneous structure (its two elements may be of different types).