Unpacking array/collection in Java

Viewed 1768

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

3 Answers

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.

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.

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

Related