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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12328327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:27:17  来源:igfitidea点击:

Java - quick way of assigning array values to individual variables

javaarrayssyntaxvariable-assignment

提问by Michael

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

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

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

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

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.

提前致谢。

采纳答案by Adam Mihalcin

No, there is no such syntax in Java.

不,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

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

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

or in F# you can write

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

回答by fastcodejava

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]);

回答by Lemon Juice

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.

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

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);

String[] 字符串 = str.split(":", 2);

List keepStrings = new ArrayList();

for(int i=0;i<strings.length;i++)
{
    String string = strings[i];

    keepStrings.add(string);


}