6

In Python and C#, if you have a tuple/list you can unpack it with the following:

tup = (1, 3)
a, b = tup

Then a = 1 and b = 3.

It seems to me that Java doesn't have tuples, but if I have a Vector or primitive [] array of known size, is there a similar unpacking idiom for arrays/vectors in Java? At the moment I am using the below solution.

a = arr[0]
b = arr[1]

Where arr is a stand-in for a real tuple.

I'm open to any answer which accomplishes a similar behavior, even if it involves external libraries/additional classes/etc

shayaan
  • 1,482
  • 1
  • 15
  • 32

3 Answers3

2

No, it is not possible to unpack tuples, vectors, arrays, nor any other collection type in this way in Java.

External libraries will not help you as this is a matter for the language itself.

Joe C
  • 15,324
  • 8
  • 38
  • 50
0

Java does not have tuples. There is no way to return multiple elements and then store them in multiple variables. All you can do is return an object with multiple fields. However, that can in no way be equivalent of a tuple.

Mohan
  • 334
  • 2
  • 12
  • 2
    Not only is this wrong (Java does have tuples in the standard library), but you can always return multiple objects in the form of an array or list. There's just no built in way to unpack them it seems. – DeeJayh Mar 22 '21 at 08:04
0

You may use Pair from in javafx.util.Pair.

Jack
  • 165
  • 2
  • 10