Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - quick way of assigning array values to individual variables

I have a method which will return two strings in an array, split(str, ":", 2) to be precise.

Is there a quicker way in java to assign the two values in the array to string variables than

String[] strings = str.split(":", 2);
String string1 = strings[0];
String string2 = strings[1];

For example is there a syntax like

String<string1, string2> = str.split(":", 2);

Thanks in advance.

like image 339
Michael Avatar asked Sep 08 '12 05:09

Michael


People also ask

How do you assign an array value to a variable in Java?

First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

How do you convert an array to an individual variable?

Extract() is a very popular function that converts elements in an array into variables in their own right. Extract takes a minimum of one parameter, an array, and returns the number of elements extracted.

How do you assign an array to a variable?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.


2 Answers

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 *)
like image 102
Adam Mihalcin Avatar answered Sep 28 '22 14:09

Adam Mihalcin


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]);
like image 40
fastcodejava Avatar answered Sep 28 '22 14:09

fastcodejava