我应该将初始 java String 值从 null 设置为 "" 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1277965/
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
Should I set the initial java String values from null to ""?
提问by Martlark
Often I have a class as such:
我经常有这样的课程:
public class Foo
{
private String field1;
private String field2;
// etc etc etc
}
This makes the initial values of field1 and field2 equal to null. Would it be better to have all my String class fields as follows?
这使得 field1 和 field2 的初始值等于 null。将我所有的 String 类字段如下所示会更好吗?
public class Foo
{
private String field1 = "";
private String field2 = "";
// etc etc etc
}
Then, if I'm consistent with class definition I'd avoid a lot of null pointer problems. What are the problems with this approach?
然后,如果我与类定义一致,我将避免很多空指针问题。这种方法有什么问题?
采纳答案by John O
I disagree with the other posters. Using the empty string is acceptable. I prefer to use it whenever possible.
我不同意其他海报。使用空字符串是可以接受的。我更喜欢尽可能使用它。
In the great majority of cases, a null String and an empty String represent the exact same thing - unknown data. Whether you represent that with a null or an empty String is a matter of choice.
在绝大多数情况下,空字符串和空字符串表示完全相同的东西——未知数据。是否用 null 或空字符串表示它是一个选择问题。
回答by Paul Tomblin
Absolutely not. An empty string and a null string are entirely different things and you should not confuse them.
绝对不。空字符串和空字符串是完全不同的东西,您不应该混淆它们。
To explain further:
进一步解释:
- "null" means "I haven't initialized this variable, or it has no value"
- "empty string" means "I know what the value is, it's empty".
- “null”表示“我还没有初始化这个变量,或者它没有值”
- “空字符串”的意思是“我知道值是什么,它是空的”。
As Yuliy already mentioned, if you're seeing a lot of null pointer exceptions, it's because you are expecting things to have values when they don't, or you're being sloppy about initializing things before you use them. In either case, you should take the time to program properly - make sure things that should have values have those values, and make sure that if you're accessing the values of things that might not have value, that you take that into account.
正如 Yuliy 已经提到的,如果您看到很多空指针异常,那是因为您期望事物具有值而它们没有,或者您在使用它们之前对初始化事物草率。在任何一种情况下,您都应该花时间正确编程 - 确保应该具有值的事物具有这些值,并确保如果您正在访问可能没有价值的事物的值,您将其考虑在内。
回答by NSherwin
I would avoid doing this, you need to know if your instances aren't getting populated with data correctly.
我会避免这样做,您需要知道您的实例是否没有正确填充数据。
回答by Yuliy
That way lies madness (usually). If you're running into a lot of null pointer problems, that's because you're trying to use them before actually populating them. Those null pointer problems are loud obnoxious warning sirens telling you where that use is, allowing you to then go in and fix the problem. If you just initially set them to empty, then you'll be risking using them instead of what you were actually expecting there.
那种方式是疯狂的(通常)。如果您遇到很多空指针问题,那是因为您在实际填充它们之前尝试使用它们。那些空指针问题是响亮的令人讨厌的警告警报,告诉您该用途在哪里,然后您可以进入并解决问题。如果您最初只是将它们设置为空,那么您将冒着使用它们而不是您实际期望的风险。
回答by Eric Petroelje
Generally it would be best to avoid this. A couple of reasons:
通常最好避免这种情况。几个原因:
Getting a NullPointerException is generally a good warning that you are using a variable before you should be, or that you forgot to set it. Setting it to an empty string would get rid of the NullPointerException, but would likely cause a different (and harder to track down) bug further down the line in your program.
There can be a valid difference between null and "". A null value usually indicates that no value was set or the value is unknown. An empty string indicates that it was deliberately set to be empty. Depending on your program, that subtle difference could be important.
获得 NullPointerException 通常是一个很好的警告,表明您在应该使用变量之前使用了变量,或者您忘记了设置它。将其设置为空字符串将摆脱 NullPointerException,但可能会导致程序中更进一步的不同(并且更难追踪)错误。
null 和 "" 之间可能存在有效差异。空值通常表示未设置值或值未知。空字符串表示它是故意设置为空的。根据您的程序,这种细微的差异可能很重要。
回答by Michael Borgwardt
Does it actually make sense in a specific case for the value to be used before it is set somewhere else, and to behave as an empty String in that case? i.e. is an empty string actually a correct default value, and does it make sense to have a default value at all?
在特定情况下,在将值设置在其他地方之前使用该值并在这种情况下表现为空字符串实际上是否有意义?ie 是一个空字符串实际上是一个正确的默认值,有一个默认值是否有意义?
If the answer is yes, setting it to "" in the declaration is the right thing to do. If not, it's a recipe for making bugs harder to find and diagnose.
如果答案是肯定的,那么在声明中将其设置为 "" 是正确的做法。如果没有,这就是使错误更难发现和诊断的秘诀。
回答by vsingh
No way. Why do you want to do that? That will give incorrect results. nulls and """ are not same.
没门。你为什么要这样做?这将给出不正确的结果。空值和“””不一样。
回答by vinaynag
Null is better, that is why they are called unchecked exceptions {Null pointer exception}. When the exception is thrown, it tells you that you have to initialize it to some non null value before calling any methods on it.
Null 更好,这就是为什么它们被称为未经检查的异常 {Null 指针异常}。当抛出异常时,它告诉您必须在调用任何方法之前将其初始化为某个非空值。
If you do
如果你这样做
private String field1 = "";
私人字符串字段1 =“”;
You are trying to supress the error. It is hard to find the bug, later.
您正在尝试抑制错误。以后很难找到错误。
回答by Peter Lawrey
I would suggest neither.
我不建议。
Instead you should give your fields sensible values. If they don't have to change, I would make them final.
相反,您应该为您的字段提供合理的值。如果他们不必改变,我会让他们成为最终的。
public class Foo {
private final String field1;
private final String field2;
public Foo(String field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}
// etc.
}
No need to assign, i'm-not-initialised-yet values. Just give it the initial values.
无需分配,我尚未初始化值。只需给它初始值。
回答by Nilesh Tailor
I know this is an old question but I wanted to point out the following:
我知道这是一个老问题,但我想指出以下几点:
String s = null;
s += "hello";
System.out.println(s);// this will return nullhello
whereas
然而
String s = "";
s += "hello";
System.out.println(s); // this will return hello
obviously the really answer to this is that one should use StringBuffer rather than just concatenate strings but as we all know that for some code it is just simpler to concatenate.
显然,真正的答案是应该使用 StringBuffer 而不是仅仅连接字符串,但众所周知,对于某些代码,连接更简单。