5

In Perl, I can say:

my @list = ( 1, 2, 3 );
my ( $a, $b, $c ) = @list;

In Java, as far as I can tell, I need to do this:

List<Integer> list = { 1, 2, 3 };
int a = list.get(0);
int b = list.get(1);
int c = list.get(2);

Does there exist some kind of syntactic sugar that will let me assign all three variables in a single line of code, like Perl?

John Arrowwood
  • 2,370
  • 2
  • 21
  • 32
  • 3
    Java doesn't have anything like tuple unpacking. But you can do that in one statement, though (not particularly helpful): `int a = list.get(0), b = list.get(1), c = list.get(2);` – ernest_k Jul 31 '18 at 19:38
  • What ernest_k said is about as good as it gets with Java, I think, unless you wrote a method that emulates this functionality. – NAMS Jul 31 '18 at 19:48
  • You can create own functional interface 'populate' for example, pass to there result and array, populate somehow, as you wish) – lord_hokage Jul 31 '18 at 19:48
  • Possible duplicate of [Initialization of an ArrayList in one line](https://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line) – user43968 Jul 31 '18 at 20:05
  • Good to know that it wasn't just my own inability to find it, that it really doesn't exist. Thanks. – John Arrowwood Aug 01 '18 at 14:26
  • 1
    @ernest_k well not exactly what I wanted, but much cleaner than adding a line per variable. Good tip. – Alain Cruz Mar 18 '23 at 15:42

1 Answers1

0

Can't leave a comment, but want to say that what @ernest_k posted assigning multiple variables on one line in the comment above is a good catch. My code is much cleaner now, thanks!

int a = list.get(0), b = list.get(1), c = list.get(2);

Also works with simple arrays and final keyword if anyone is wondering:

final String a = array[0], b = array[1], c = array[2];