我应该将初始 java 字符串值从 null 设置为“"吗? [英] Should I set the initial java String values from null to ""?

查看:21
本文介绍了我应该将初始 java 字符串值从 null 设置为“"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常有这样的课程:

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.

这篇关于我应该将初始 java 字符串值从 null 设置为“"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆