Java 声明多个 String 变量并一次性将它们全部初始化为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6505921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:26:40  来源:igfitidea点击:

Declare multiple String variables and initialize them to all to null at once

java

提问by asda

I want to declare all of them null. Am I doing someting wrong or is this the right method?

我想宣布所有这些null。我做错了什么还是这是正确的方法?

String a = null, b = null, c = null, d = null;

(Is there any more compact syntax for doing this?)

(有没有更紧凑的语法来做到这一点?)

采纳答案by aioobe

Yep. That's the way to do it.

是的。这就是这样做的方法。

You could also do

你也可以这样做

String a, b, c, d;
a = b = c = d = null;

The line below however won't compile:

但是下面的行不会编译:

String a = b = c = d = null;  // illegal

(Note that if these are member variables, they will be initialized to nullautomatically.)

(请注意,如果这些是成员变量,它们将被null自动初始化。)

回答by gulyan

You may want something like this:

你可能想要这样的东西:

String a, b, c, d = a = b = c = null;

回答by tskuzzy

That's perfectly valid. I suppose a slightly shorter way of doing it is:

这是完全正确的。我想一个稍微短一点的方法是:

String a, b, c, d;
a = b = c = d = null;

回答by Paul Cager

Yes, that's how o do it.

是的,就是这样做的。

However, if you find yourself writing that sort of construct often in might be a sign that you are declaring a variable too early, before you know what value to put in it:

但是,如果您发现自己经常编写这种结构,则可能表明您在不知道要放入什么值之前过早地声明了一个变量:

http://www.javapractices.com/topic/TopicAction.do?Id=126

http://www.javapractices.com/topic/TopicAction.do?Id=126

Edit:You might alsdo want to look at this:

编辑:您可能还想看看这个:

http://www.javapractices.com/topic/TopicAction.do?Id=14

http://www.javapractices.com/topic/TopicAction.do?Id=14

回答by lkisac

If you're setting it to null,

如果您将其设置为null

String a, b, c, d;

would be enough as the declaration would set it to null by default. See thisthread for further explanation.

就足够了,因为默认情况下声明会将其设置为 null。请参阅线程以获取进一步说明。

Otherwise if you're setting a, b, c, dto some value, you would have to use the solutions mentioned above.

否则,如果您设置a, b, c, d为某个值,则必须使用上述解决方案。