2

In Python you can do the following:

myList = [1, 2, 3, 4]
a, b, c, d = myList
print a # -> 1
print d # -> 4

Is there a way to do such a thing in Java? Better/faster than below:

int[] myList= {1, 2, 3, 4};
int a = myList[0];
int b = myList[1];
int c = myList[2];
int d = myList[3];
3

2 Answers 2

1

Not exactly the same but you can get close to it by using comma operator:

int[] myList= {1, 2, 3, 4};
int a = myList[0], b = myList[1], c = myList[2], d = myList[3];
Sign up to request clarification or add additional context in comments.

Comments

0

You could use an ArrayList of type Integer.

This would look like the following code:

List<Integer> myList = new ArrayList<Integer>();

Then you can set variables by using .set(int where, int what)

myList.set(0,1);

Or you can just append with .add(int what)

myList.add(2);

Then you can get the variables by using .get(int where)

int a = myList.get(0);
int b = myList.get(1);

This sets variable a to 1 and variable b to 2, because you append it at the very end. The advantage of those ArrayLists are, that you can get variables more easy than with Array, but you need a litte bit more code to add it. So its good for a big pool of non-changing variables in your code.

1 Comment

"you can get variables more easy than with Array" ... how is int a = myList.get(0); "more easy" than int a = myList[0];? And btw myList.set(0,1); won't work if there is no index 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.