在Java中将多个变量初始化为相同的值 [英] Initializing multiple variables to the same value in Java

查看:39
本文介绍了在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 = ""

这是可以在java中做的事情吗?牢记效率.

Is this something that is possible to do in java? Keeping efficiency in mind.

推荐答案

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

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

This should work with immutable objects. It doesn't make any sense for mutable objects for example:

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

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

All the variables would be pointing to the same instance. Probably what you would need in that case is:

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

或者更好的是使用数组或 集合.

Or better yet use an array or a Collection.

这篇关于在Java中将多个变量初始化为相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆