Should I set the initial java String values from null to quot;quot;?(我应该将初始 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 设置为“"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我应该将初始 java 字符串值从 null 设置为“"吗?
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
