Java String 方法(本地)变量应该初始化为 null 还是 ""?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5478996/
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-10-30 11:18:25  来源:igfitidea点击:

Should Java String method (local) variables be initialized to null or ""?

javastring

提问by Canam

What is the best practice for initializing a String method (local) variable to avoid the "Variable might not have been initialized" error in Java?

初始化 String 方法(本地)变量以避免 Java 中的“变量可能尚未初始化”错误的最佳实践是什么?

String s=null; or String s="";

字符串 s=null; 或字符串 s="";

Does it make a difference? If so, which one is better and why?

这有什么不同吗?如果是这样,哪个更好,为什么?

I've read conflicting answers on the web.

我在网上阅读了相互矛盾的答案。

Thanks!

谢谢!

回答by Jon Skeet

Yes, it makes a difference. One is a reference to an empty string, one is a null reference. They're not the same.

是的,它有所作为。一个是对空字符串的引用,一个是空引用。他们不一样。

Which is better? It depends whether you want a null value or a reference to an empty string... they behave differently, so pick the one which behaves the way you want it to.

哪个更好?这取决于您想要空值还是对空字符串的引用……它们的行为不同,因此请选择按照您希望的方式运行的那个。

I rarely need to assign a "dummy" value to a variable though - usually just initializing the variable at the point of declaration with the realvalue I want is fine. If you can give us more context, we may be able to help you structure your code better so this isn't a problem for you.

我很少需要为变量分配一个“虚拟”值 - 通常只需在声明点用我想要的真实值初始化变量就可以了。如果您能给我们更多的上下文,我们或许能够帮助您更好地构建代码,因此这对您来说不是问题。

回答by Garrett Hall

Best practice is to make as many fields final as possible or use default values to avoid clients instantiating bad or incomplete objects. If it makes sense for the field to be an empty string by default (i.e. it will not risk logic errors) then by all means do it that way. Otherwise, at least null will throw an exception when a client invokes a method on an object that hasn't been properly instantiated.

最佳实践是将尽可能多的字段设为 final 或使用默认值以避免客户端实例化错误或不完整的对象。如果该字段默认为空字符串是有意义的(即它不会冒逻辑错误的风险),那么一定要这样做。否则,当客户端调用尚未正确实例化的对象的方法时,至少 null 将引发异常。

So in general, try to force client code to create complete objects during construction. If you don't know what the string should be at construction time, then have them pass it in as a parameter. If the string is just used for internal logic, it may be better as a local variable or parameter - and in that case I generally prefer null to "" because == null is more explicit than isEmpty().

所以一般来说,在构造过程中尽量强制客户端代码创建完整的对象。如果您在构造时不知道字符串应该是什么,那么让他们将其作为参数传入。如果字符串仅用于内部逻辑,则作为局部变量或参数可能更好 - 在这种情况下,我通常更喜欢 null 而不是 "",因为 == null 比 isEmpty() 更明确。

回答by tvkanters

It all depends on what you want your program to do. Sometimes it can be useful to see whether a string has been set already or not at which nullwould be best. Other times you want to prevent NullPointers which makes ""better.

这完全取决于您希望您的程序做什么。有时,查看字符串是否已经设置null为最佳位置会很有用。其他时候你想防止 NullPointers 变得""更好。

回答by lukastymo

It's really depends what you're doing in your program.

这真的取决于你在你的程序中做什么。

"" (empty string) is connected only with String and it's safer than null. When you call methods from String class for example: replaceAll(), indexOf() the program will work correctly butwhen you have null, you have NullPointerException all time when you're calling method on it.

""(空字符串)仅与 String 连接,它比 null 更安全。当您从 String 类调用方法时,例如:replaceAll(), indexOf() 程序将正常工作,但是当您有 null 时,您在调用方法时总是会遇到 NullPointerException。

Consider if string empty value in your application is not something bad to you, then choose str="".

考虑应用程序中的字符串空值是否对您不利,然后选择 str=""。

Notice that very often is better when NullPointerException is thrown because we know about an invalid state in our application, so when you want know about this set String to null by default.

请注意,抛出 NullPointerException 时通常会更好,因为我们知道应用程序中存在无效状态,因此当您想知道此设置时,默认情况下将 String 设置为 null。

回答by TheDude

I prefer to initialize a String in Java as "", purely because I try to avoid null pointers. Null pointers add a lot of overhead that can be removed by assigning "" instead of null.

我更喜欢将 Java 中的字符串初始化为 "",纯粹是因为我试图避免使用空指针。空指针增加了很多开销,可以通过分配 "" 而不是 null 来消除这些开销。

回答by Pa?lo Ebermann

Most often I would say: don't initialize your local variable at all when declaring it, if it would be a dummy value like ""or null. Put the real value in, or wait until you can put it in.

大多数时候我会说:在声明它时根本不要初始化你的局部变量,如果它是一个像""or那样的虚拟值null。把真正的价值放进去,或者等到你能把它放进去。

The compiler then will make sure that there is at least one assignment before any possible use of the variable. Only for the seldom cases where the compiler isn't smart enough to figure this out (since it needs information not available to it locally) I would use some initialization, and then usually nullis better since it shows with a NullPointerException when I was wrong. (I might add an assert s != nullafter the point where I think the Initialization should be done to enforce this.)

然后编译器将确保在任何可能的变量使用之前至少有一个赋值。仅在极少数情况下,编译器不够聪明,无法解决这个问题(因为它需要本地无法获得的信息),我会使用一些初始化,然后通常null会更好,因为当我出错时它会显示 NullPointerException。(我可能会assert s != null在我认为应该进行初始化以强制执行这一点之后添加一个。)