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

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

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

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

例如,有一个类似的语法

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

提前致谢。

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

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

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

或者在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 *) 

您可以创建持有者类:

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

然后你可以这样做:

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

我可以说“使用循环”。 可能是for循环,可能是while,这取决于你。 如果这样做,则不必担心数组大小。 一旦您将数组大小作为“终止条件”传递,它将顺利运行。

更新:

我将使用如下代码。 无论如何我没有去过它,但我总是使用这种风格。

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

 List keepStrings = new ArrayList(); for(int i=0;i