Java - quick way of assigning array values to individual variables Java - quick way of assigning array values to individual variables arrays arrays

Java - quick way of assigning array values to individual variables


No, there is no such syntax in Java.

However, some other languages have such syntax. Examples include Python's tuple unpacking, and pattern matching in many functional languages. For example, in Python you can write

 string1, string2 = text.split(':', 2) # Use string1 and string2

or in F# you can write

 match text.Split([| ':' |], 2) with | [string1, string2] -> (* Some code that uses string1 and string2 *) | _ -> (* Throw an exception or otherwise handle the case of text having no colon *)


You can create a holder class :

public class Holder<L, R> {    private L left;    private R right;   // create a constructor with left and right}

Then you can do :

Holder<String, String> holder = new Holder(strings[0], strings[1]);


I can say "Use Loops". May be for loops, may be while, that depends on you. If you do so, you don't have to worry about the array size. Once you have passed the array size as the "termination condition" it will work smoothly.

UPDATE:

I will use a code like below. I didn't runt it anyway, but I use this style always.

String[] strings = str.split(":", 2);

List keepStrings = new ArrayList();for(int i=0;i<strings.length;i++){    String string = strings[i];    keepStrings.add(string);}