使一个空字符串值得吗? [英] Is making an empty string constant worth it?
本文介绍了使一个空字符串值得吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个同事发誓
//in a singleton "Constants" class
public static final String EMPTY_STRING = "";
在整个项目中可用的常量类中。这样,我们可以编写类似
in a constants class available throughout the project. That way, we can write something like
if (Constants.EMPTY_STRING.equals(otherString)) {
...
}
而不是
if ("".equals(otherString)) {
...
}
我说它是
- 不值得 - 它不会节省任何空间在堆/堆栈/字符串池中,
- 丑陋
- 滥用常量类。
这里的白痴是谁?
推荐答案
字符串文字是默认实习的,所以无论你在代码中引用多少次,都只会有一个空的String对象。我认为声明EMPTY_STRING没有任何好处。否则,您也可以为整数文字声明一个,两个,三个,四个等。
String literals are interned by default, so no matter how many times you refer to "" in code, there will only be one empty String object. I don't see any benefit in declaring EMPTY_STRING. Otherwise, you might as well declare ONE, TWO, THREE, FOUR, etc. for integer literals.
当然,如果您想稍后更改EMPTY_STRING的值,把它放在一个地方很方便;)
Of course, if you want to change the value of EMPTY_STRING later, it's handy to have it in one place ;)
这篇关于使一个空字符串值得吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文