在Java中将多个变量初始化为相同的值
我正在寻找一种干净有效的方法来声明相同类型和相同值的多个变量。现在我有:
String one = "", two = "", three = "" etc...
但我正在寻找类似的东西:
String one,two,three = ""
这是可以在java中做的事情吗?牢记效率。
I'm looking for a clean and efficient method of declaring multiple variables of the same type and of the same value. Right now I have:
String one = "", two = "", three = "" etc...
But I'm looking for something like:
String one,two,three = ""
Is this something that is possible to do in java? Keeping efficiency in mind.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这应该适用于不可变的对象。例如,对于可变对象来说,它没有任何意义:
所有变量都指向同一个实例。在这种情况下您可能需要的是:
或者更好地使用数组或
集合
。This should work with immutable objects. It doesn't make any sense for mutable objects for example:
All the variables would be pointing to the same instance. Probably what you would need in that case is:
Or better yet use an array or a
Collection
.您可以声明多个变量,并初始化多个变量,但不能同时初始化这两个变量:
但是,大多数 Java 开发人员都会不赞成这种事情(尤其是多重赋值),他们会认为这是相反的 /em>“视觉上简单”。
You can declare multiple variables, and initialize multiple variables, but not both at the same time:
However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".
不,这在java中是不可能的。
你可以这样做..但是尽量避免它。
No, it's not possible in java.
You can do this way .. But try to avoid it.
适用于基元和不可变类,例如字符串、包装类字符、字节。
对于可变类,
创建了 3 个引用 + 1 个对象。所有引用都指向同一个对象,您的程序将出现错误。
Works for primitives and immutable classes like
String
, Wrapper classes Character, Byte.For mutable classes
Three references + one object are created. All references point to the same object and your program will misbehave.
你可以这样做:
但是这些都将指向同一个实例。它不会导致最终变量或原始类型出现问题。这样,您就可以在一行中完成所有操作。
You can do this:
But these will all point to the same instance. It won't cause problems with final variables or primitive types. This way, you can do everything in one line.
我认为您不可能必须单独设置所有值(如您提供的第一个示例)。
您给出的第二个示例只会将最后一个变量初始化为“”,而不是其他变量。
I do not think that is possible you have to set all the values individualling (like the first example you provided.)
The Second example you gave, will only Initialize the last varuable to "" and not the others.
编辑:正如 Zeeen 指出的那样,这在 Java 中不起作用。我本来想回答的问题也在 Groovy 中,这是错误提交的。
太晚了,但我发现的最简单的方法是:
输出:
Edit: As Zeeen pointed out this will not work in Java. The question I'd intended to answer was in Groovy as well, this was submitted in error.
Way too late to this but the simplest way I've found is:
Output: