Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel assignment in Java?

Tags:

Does Java have something similar to Python's [a, b, c] = (1, 2, 3) or PHP's list($a, $b, $c) = array(1, 2, 3)?

like image 570
powerboy Avatar asked May 06 '11 22:05

powerboy


2 Answers

Not really. You can do x = y = 0 to set several variables, but not a parallel assignment like Python.

like image 75
Charlie Martin Avatar answered Sep 28 '22 07:09

Charlie Martin


Python's multiple assignment is fairly powerful in that it can also be used for parallel assignment, like this:

(x,y) = (y,x) # Swap x and y

There is no equivalent for parallel assignment in Java; you'd have to use a temporary variable:

t = x; x = y; y = t;

You can assign several variables from expressions in a single line like this:

int a = 1, b = 2, c = 3;

Or to map from an array, you can do this:

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

If this seems too verbose, you can temporarily create a one-letter reference to your array for the assignment:

int[] t = array;
int a = t[0], b = t[1], c = t[2];

Getting more to the root of the question, multiple assignment tends to be handy in Python in situations where code is passing around several related variables (perhaps of different types) together in a list or array. In Java (or C/C++), the more idiomatic way to do this would be to create a small data class (or struct) to bundle these variables up together, and have both the producer and consumer use it. You can then refer to the fields by name instead of by index, like this:

class Foo {
    public int a;
    public int b;
    public int c;
}

/* ... */

Foo produceFoo() {
    Foo f = new Foo();
    f.a = 1;
    f.b = 2;
    f.c = 3;
    return f;
}

/* ... */

Foo f = produceFoo();
System.out.println(f.a + "," + f.b + "," + f.c);

This also opens the door to later refactoring that will make Foo a real class with behavior and encapsulated private data, not just a data class.

like image 42
Chiara Coetzee Avatar answered Sep 28 '22 08:09

Chiara Coetzee