我应该将初始java String值从null设置为“"”吗? [英] Should I set the initial java String values from null to ""?
问题描述
我经常有这样的课程:
public class Foo
{
private String field1;
private String field2;
// etc etc etc
}
这使得field1和field2的初始值等于null。拥有我的所有String类字段会更好吗?
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?
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?
推荐答案
我不同意其他海报。使用空字符串是可以接受的。我希望尽可能使用它。
I disagree with the other posters. Using the empty string is acceptable. I prefer to use it whenever possible.
在绝大多数情况下,null String和一个空String表示完全相同的东西 - 未知数据。无论您使用null还是空字符串表示,都是一个选择问题。
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.
这篇关于我应该将初始java String值从null设置为“"”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!