在Java中将多个变量初始化为相同的值我正在寻找一种干净有效的方法来声明相同类型和相同值的多个变量。现在我有:String one = "", two = "", three = "" etc...但我正在寻找类似的东西:String one,two,three = ""这是在Java中可以做的事情吗?牢记效率。
3 回答

慕斯王
TA贡献1864条经验 获得超2个赞
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();
或者更好的是使用数组或Collection
。

慕桂英4014372
TA贡献1871条经验 获得超13个赞
您可以声明多个变量,并初始化多个变量,但不能同时:
String one,two,three; one = two = three = "";
但是,大多数Java开发人员都不赞成这种事情(尤其是多项任务),他们认为它与 “视觉上简单” 相反。

千万里不及你
TA贡献1784条经验 获得超9个赞
不,这在Java中是不可能的。
你可以这样做..但试着避免它。
String one, two, three;one = two = three = "";
添加回答
举报
0/150
提交
取消