6

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?

omega
  • 40,311
  • 81
  • 251
  • 474

3 Answers3

7

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;
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
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.

yshavit
  • 42,327
  • 7
  • 87
  • 124
0

I'd prefer the variables private with getters, no setters. Set in the constructor, obviously. Then implement iterable, maybe.

anthropomo
  • 4,100
  • 1
  • 24
  • 39
  • Iterable likely isn't appropriate. `Iterable` is for something with some number of elements, all of type `T`. A tuple is, in general, a heterogeneous structure (its two elements may be of different types). – yshavit Jan 29 '13 at 03:21