我应该将初始 java 字符串值从 null 设置为“"吗?

2022-01-18 00:00:00 string initialization null java

我经常有这样的课程:

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 表示它是一个选择问题.

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.

相关文章