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?
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;
}
}
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.
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