English 中文(简体)
在Java中将多个变量初始化为相同值
原标题:Initializing multiple variables to the same value in Java

我正在寻找一种干净高效的方法来声明相同类型和相同值的多个变量。现在我有:

String one = "", two = "", three = "" etc...

但我正在寻找这样的东西:

String one,two,three = ""

这是在java中可以做到的吗?牢记效率。

最佳回答
String one, two, three;
one = two = three = "";

这应该适用于不可变的对象。它对可变对象没有任何意义,例如:

Person firstPerson, secondPerson, thirdPerson;
firstPerson = secondPerson = thirdPerson = new Person();

所有变量都指向同一个实例。在这种情况下,您可能需要:

Person firstPerson = new Person();
Person secondPerson = new Person();
Person thirdPerson = new Person();

或者最好使用数组或集合

问题回答

您可以声明多个变量并初始化多个变量,但不能同时声明和初始化这两个变量:

 String one,two,three;
 one = two = three = "";

然而,这种事情(尤其是多重赋值)会受到大多数Java开发人员的反对,他们认为这是“视觉简单”的反面。

不,这在java中是不可能的。

你可以这样做。。但是尽量避免

String one, two, three;
one = two = three = "";

适用于基元和不可变类,如<code>String</code>、Wrapper类Character、Byte。

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

对于可变类

Reference r1 = Reference r2 = Reference r3 = new Object();`  

创建了三个引用+一个对象。所有引用都指向同一个对象,您的程序将出现错误行为。

您可以执行以下操作:

String one, two, three = two = one = "";

但这些都指向同一个例子。它不会导致最终变量或基元类型出现问题。这样,你就可以在一行中完成所有事情。

我认为这是不可能的,你必须个性化地设置所有的值(就像你提供的第一个例子一样)

您给出的第二个示例只会将最后一个变量初始化为“”,而不会初始化其他变量。

编辑:正如Zeeen所指出的,这在Java中是行不通的。我想回答的问题也是在Groovy中,这是错误提交的。


虽然为时已晚,但我找到的最简单的方法是:

String foo = bar = baz = "hello"
println(foo)
println(bar)
println(baz)

输出:

hello
hello
hello




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签