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
  • 35,693
  • 74
  • 215
  • 425

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
  • 299,921
  • 44
  • 364
  • 552
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
  • 41,077
  • 7
  • 83
  • 120
0

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

anthropomo
  • 4,032
  • 1
  • 23
  • 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