Java - 将数组值分配给单个变量的快速方法

Mic*_*ael 9 java arrays syntax variable-assignment

我有一个方法,split(str, ":", 2)准确地返回一个数组中的两个字符串.

在java中是否有更快的方法将数组中的两个值分配给字符串变量

String[] strings = str.split(":", 2);
String string1 = strings[0];
String string2 = strings[1];
Run Code Online (Sandbox Code Playgroud)

例如,有一个类似的语法

String<string1, string2> = str.split(":", 2);
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Ada*_*cin 6

不,Java中没有这样的语法.

但是,其他一些语言也有这样的语法.示例包括Python的元组解包和许多函数语言中的模式匹配.例如,在Python中你可以写

 string1, string2 = text.split(':', 2)
 # Use string1 and string2
Run Code Online (Sandbox Code Playgroud)

或者在F#中你可以写

 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 *)
Run Code Online (Sandbox Code Playgroud)