java初始化变量的值,在Java中将多个变量初始化为相同的值

本文探讨了在Java中通过简洁方式声明多个同类型变量的方法,如使用逗号分隔和赋同一初始值。特别关注了字符串(String)和不可变对象的一致性,以及在处理可变对象时的正确实例化技巧。讨论了数组、集合和独立实例的选择。
摘要由CSDN通过智能技术生成

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值