Java字符串初始化

发布于 2024-09-10 19:34:22 字数 330 浏览 6 评论 0原文

您更喜欢哪个以及为什么”

String myString = null;
if(someCondition)
   myString = "something";
else
   myString = "something else";

或者

String myString = "";
if(someCondition)
   myString = "something";
else
   myString = "something else";

我知道可以使用三元 (?:) 运算符,但我想了解以上两个。

Which do you prefer and why"

String myString = null;
if(someCondition)
   myString = "something";
else
   myString = "something else";

OR

String myString = "";
if(someCondition)
   myString = "something";
else
   myString = "something else";

I know that using the ternary (? :) operator is possible but I'd like to know about the above two.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

蘸点软妹酱 2024-09-17 19:34:23

惯用的方法是使用三元/条件运算符 (JLS 15.25 ):

String myString = (someCondition ? "something" : "something else");

但是如果您确实觉得必须这样做,您也可以执行更详细的 if-else 语句:

final String myString;
if(someCondition) {
   myString = "something";
} else {
   myString = "something else";
}

请注意,我在上面添加了 final 修饰符片段。如果您计划进一步重新分配该变量,那么它当然不能是final,因此您可以删除修饰符,当然代码仍然可以工作。


为什么是最终

上面代码片段中 final 的要点是表明 if-else 构造将在所有可能的情况下分配给 myString 一次且恰好一次执行路径。这是所提议的 if-else 解决方案的主要思想:如果您只想为局部变量赋值一次,即使它可能是多种可能性之一,那么请将其设为< code>final 以增强可读性。

与此“替代”提案进行对比:

// DON'T DO THIS! Example only!
String myString = "something else";
if (someCondition) myString = "something";

使用此构造,您可能会分配给 myString 两次,因此即使没有,您也不能将 final 放在这里进一步重新分配。您也不能将 final 放入原始 = null;= ""; 提案中,这是主要的之一不推荐它们的原因。

如果您只是想在使用变量之前覆盖它,那么为变量赋值是没有意义的。它会损害可读性,甚至可能隐藏错误,例如,当一个执行路径无法覆盖此“初始”值时。

参考文献


总结

  • 如果您无论如何都要覆盖局部变量,请不要仅仅为了这样做而“初始化”它
    • 让它处于未初始化状态,这样编译器就可以通过指出该变量尚未初始化时的任何使用来帮助您识别可能的错误
    • 如果代码编译通过,则在所有使用之前至少一次为该变量分配一个“真实”值
  • 如果不需要重新分配局部变量,请将其设为final以增强可读性
    • final 立即向读者保证,不可能进一步重新分配
    • 编译器可以帮助您防止犯后续重新分配的错误
    • 如果代码编译通过,则在所有使用之前为变量分配一个“真实”值一次

  • 一般来说,您应该让编译器帮助您编写最好、最易读的代码。

The idiomatic way is to use ternary/conditional operator (JLS 15.25):

String myString = (someCondition ? "something" : "something else");

But you can also do the more verbose if-else statement if you really feel you must:

final String myString;
if(someCondition) {
   myString = "something";
} else {
   myString = "something else";
}

Note that I've added final modifier in the above snippet. If you're planning on further reassignments to the variable, then of course it can't be final, so you can remove the modifier and of course the code would still work.


Why final?

The point of the final in the above snippet is to show that the if-else construct will assign to myString once and exactly once in all possible execution paths. That is the main idea of the proposed if-else solution: if you're going to assign a value to a local variable only once, even if it can be one of several possibilities, then make it final to enhance readability.

Contrast that with this "alternative" proposal for example:

// DON'T DO THIS! Example only!
String myString = "something else";
if (someCondition) myString = "something";

With this construct, you may be assigning to myString twice, thus you couldn't put final here even if there was no further reassignment. You also couldn't put final in either of the original = null; or = ""; proposals, and this is one of the main reasons why they're not recommendable.

There's no point in assigning a value to a variable if you're just going to overwrite it before you're going to use it. It hurts readability, and may potentially even hide bugs, e.g. when one execution path fails to overwrite this "initial" value.

References


Summary

  • Don't "initialize" a local variable just for the sake of doing it if you're going to overwrite it anyway
    • Let it be uninitialized, so that the compiler can help you identify a possible bug by pointing out any use of the variable while it's still uninitialized
    • If the code compiles, then the variable is assigned a "real" value at least once before all uses
  • If you don't need to reassign a local variable, make it final to enhance readability
    • final immediately assures readers that no further reassignments are possible
    • The compiler can help you prevent making the mistake of subsequent reassignment
    • If the code compiles, then the variable is assigned a "real" value exactly once before all uses
  • Generally speaking, you should let the compiler help you write the best, most readable code.
逆光飞翔i 2024-09-17 19:34:23

初始化步骤不是必需的,并且可能会使未来的读者感到困惑。

我个人的观点是,这种变量只能分配一次,因此它是 final 关键字的完美候选者。

final String myString;
if (someCondition) {
   myString = "something";
} else {
   myString = "something else";
}

请注意,myString 定义不包含赋值(因为这会禁止以后的赋值),并且赋值后它是只读的。这提供了健壮的代码并更清楚地显示您的意图。

另请注意,即使对于单行,我也相信大括号。可能是 Perl 的习惯,但如果你不这样做,总有一天它会咬你一口。

The initialization step is not necessary, and may confuse future readers.

My personal opinion is that this kind of variable should only be assigned once, hence it is a perfect candidate for the final keyword.

final String myString;
if (someCondition) {
   myString = "something";
} else {
   myString = "something else";
}

Note that the myString definition does not include an assignment (as this would prohibit later assignments) and that after the assignment it is read-only. This gives robust code and shows your intent more clearly.

Please also note that I believe in braces even for single lines. Probably a Perl habit, but if you don't, it will bite you someday.

↙温凉少女 2024-09-17 19:34:23
String myString = "something else";
if(someCondition) myString = "something"; // (use curly braces if you prefer)
String myString = "something else";
if(someCondition) myString = "something"; // (use curly braces if you prefer)
一瞬间的火花 2024-09-17 19:34:23

我更喜欢第一个,因为 String myString = "" 将在池中创建其他对象

I prefer first one, because String myString = "" will create additional object in the pool

情栀口红 2024-09-17 19:34:23
String mystring = null;
mystring.length() 
// Cause error

上面会因空指针而导致错误。

string myString = new String();
myString.length()
// will not cause error

我喜欢稍后使用,但我认为这是个人喜好。

String mystring = null;
mystring.length() 
// Cause error

Above will cause error due to null pointer.

string myString = new String();
myString.length()
// will not cause error

I like to use later, but I think it's personal preference.

熟人话多 2024-09-17 19:34:23

下面的代码怎么样,无论如何他想设置一些东西。

String myString = (someCondition)  ? "something " : "else something";

或者

String myString = "else something"; 

if (someCondition)
   myString = "something";

在上面的情况下,如果您 90% 确定 someCondition 始终为 true。否则在声明中创建不必要的对象。期待专家的评论。

How about this follwing code ,anyways he wants to set something.

String myString = (someCondition)  ? "something " : "else something";

or this

String myString = "else something"; 

if (someCondition)
   myString = "something";

in the above case , if you are 90% sure that someCondition is always true. otherwise unnecessary object creation in declaration.Expecting comments from Gurus.

川水往事 2024-09-17 19:34:22

两者都不。相反,这样:

String myString;
if (someCondition)
   myString = "something";
else
   myString = "something else";

在您的两种选择中,变量都使用永远不会被读取的值进行初始化。它的存在这一事实具有误导性。

当然,我实际上会使用条件运算符 - 但除此之外,以上是更好的选择。

Neither. Instead, this:

String myString;
if (someCondition)
   myString = "something";
else
   myString = "something else";

In both of your alternatives, the variable is initialized with a value which will never ever be read. The fact that it's present at all is misleading.

I would actually use the conditional operator, of course - but barring that, the above is the better option.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文