为什么 Java 中没有 String.Empty?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3450604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is there no String.Empty in Java?
提问by Tom Tresansky
I understand that every time I type the string literal ""
, the same String object is referenced in the string pool.
我知道每次输入字符串文字时""
,字符串池中都会引用相同的 String 对象。
But why doesn't the String API include a public static final String Empty = "";
, so I could use references to String.Empty
?
但是为什么 String API 不包含 a public static final String Empty = "";
,所以我可以使用对 的引用String.Empty
?
It would save on compile time, at the very least, since the compiler would know to reference the existing String, and not have to check if it had already been created for reuse, right? And personally I think a proliferation of string literals, especially tiny ones, in many cases is a "code smell".
它至少可以节省编译时间,因为编译器会知道引用现有的字符串,而不必检查它是否已经创建以供重用,对吗?我个人认为,在许多情况下,字符串文字的激增,尤其是小文字,是一种“代码异味”。
So was there a Grand Design Reason behind no String.Empty, or did the language creators simply not share my views?
那么,在没有 String.Empty 的背后是否有一个宏伟的设计原因,或者语言创建者根本不同意我的观点?
采纳答案by Noel M
String.EMPTY
is 12 characters, and ""
is two, and they would both be referencing exactly the same instance in memory at runtime. I'm not entirely sure why String.EMPTY
would save on compile time, in fact I think it would be the latter.
String.EMPTY
是 12 个字符,并且""
是两个,并且它们都将在运行时引用内存中完全相同的实例。我不完全确定为什么String.EMPTY
要节省编译时间,事实上我认为应该是后者。
Especially considering String
s are immutable, it's not like you can first get an empty String, and perform some operations on it - best to use a StringBuilder
(or StringBuffer
if you want to be thread-safe) and turn that into a String.
特别是考虑到String
s 是不可变的,它不像您可以先获得一个空字符串,然后对其执行一些操作 - 最好使用 a StringBuilder
(或者StringBuffer
如果您想成为线程安全的)并将其转换为字符串。
Update
From your comment to the question:
更新
从您的评论到问题:
What inspired this is actually
TextBox.setText("");
这实际上是什么启发了
TextBox.setText("");
I believe it would be totally legitimate to provide a constant in your appropriate class:
我相信在适当的类中提供常量是完全合法的:
private static final String EMPTY_STRING = "";
And then reference it as in your code as
然后在您的代码中将其引用为
TextBox.setText(EMPTY_STRING);
As this way at least you are explicit that you want an empty String, rather than you forgot to fill in the String in your IDE or something similar.
通过这种方式,至少您明确表示想要一个空字符串,而不是忘记在 IDE 或类似的东西中填写字符串。
回答by Donal Fellows
All those ""
literals are the same object. Why make all that extra complexity? It's just longer to type and less clear (the cost to the compiler is minimal). Since Java's strings are immutable objects, there's never any need at all to distinguish between them except possibly as an efficiency thing, but with the empty string literal that's not a big deal.
所有这些""
文字都是同一个对象。为什么要增加所有额外的复杂性?只是输入时间更长,不太清楚(编译器的成本最小)。由于 Java 的字符串是不可变对象,因此根本没有必要区分它们,除非可能是为了提高效率,但使用空字符串文字并不是什么大问题。
If you really want an EmptyString
constant, make it yourself. But all it will do is encourage even more verbose code; there will neverbe any benefit to doing so.
如果你真的想要一个EmptyString
常数,那就自己做。但它所做的只是鼓励更冗长的代码;有将永远是任何利益这样做。
回答by Nikita Rybak
I understand that every time I type the String literal "", the same String object is referenced in the String pool.
There's no such guarantee made. And you can't rely on it in your application, it's completely up to jvm to decide.
我知道每次输入字符串文字“”时,都会在字符串池中引用相同的字符串对象。
没有这样的保证。而且你不能在你的应用程序中依赖它,这完全取决于 jvm 来决定。
or did the language creators simply not share my views?
Yep. To me, it seems very low priority thing.
还是语言创造者根本不同意我的观点?
是的。对我来说,这似乎是非常低优先级的事情。
回答by Freiheit
Apache StringUtils addresses this problem too.
Apache StringUtils 也解决了这个问题。
Failings of the other options:
其他选项的失败:
- isEmpty() - not null safe. If the string is null, throws an NPE
- length() == 0 - again not null safe. Also does not take into account whitespace strings.
- Comparison to EMPTY constant - May not be null safe. Whitespace problem
- isEmpty() - 非空安全。如果字符串为空,则抛出 NPE
- length() == 0 - 再次不是空安全。也不考虑空格字符串。
- 与 EMPTY 常量的比较 - 可能不是 null 安全的。空格问题
Granted StringUtils is another library to drag around, but it works very well and saves loads of time and hassle checking for nulls or gracefully handling NPEs.
授予 StringUtils 是另一个可以拖动的库,但它工作得很好并且节省了大量时间和麻烦检查空值或优雅地处理 NPE。
回答by James Black
To add on to what Noel M stated, you can look at this question, and this answer shows that the constant is reused.
要补充 Noel M 所说的内容,您可以查看此问题,此答案表明该常量已被重用。
http://forums.java.net/jive/message.jspa?messageID=17122
http://forums.java.net/jive/message.jspa?messageID=17122
String constant are always "interned" so there is not really a need for such constant.
String s=""; String t=""; boolean b=s==t; // true
字符串常量总是“实习”的,所以真的不需要这样的常量。
String s=""; String t=""; boolean b=s==t; // true
回答by Benoit Courtine
If you really want a String.EMPTY constant, you can create an utility static final class named "Constants" (for example) in your project. This class will maintain your constants, including the empty String...
如果你真的想要一个 String.EMPTY 常量,你可以在你的项目中创建一个名为“Constants”(例如)的实用程序静态最终类。此类将维护您的常量,包括空字符串...
In the same idea, you can create ZERO, ONE int constants... that don't exist in the Integer class, but like I commented, it would be a pain to write and to read :
以同样的想法,您可以创建零,一个 int 常量......在 Integer 类中不存在,但就像我评论的那样,写和读会很痛苦:
for(int i=Constants.ZERO; ...) {
if(myArray.length > Constants.ONE) {
System.out.println("More than one element");
}
}
Etc.
等等。
回答by Peter Lawrey
If you want to compare with empty string without worrying about null values you can do the following.
如果您想与空字符串进行比较而不担心空值,您可以执行以下操作。
if ("".equals(text))
Ultimately you should do what what you believe is clearest. Most programmers assume "" means empty string, not a string someone forgot to put anything into.
最终你应该做你认为最清楚的事情。大多数程序员认为 "" 表示空字符串,而不是某人忘记放入任何内容的字符串。
If you think there is a performance advantage, you should test it. If you don't think its worth testing for yourself, its a good indication it really isn't worth it.
如果您认为有性能优势,则应该对其进行测试。如果你认为它不值得为自己测试,它是一个很好的迹象,它真的不值得。
It sounds like to you try to solve a problem which was solved when the language was designed more than 15 years ago.
听起来你试图解决一个问题,这个问题在 15 年前设计语言时就已经解决了。
回答by Antony Booth
For those claiming ""
and String.Empty
are interchangeable or that ""
is better, you are very wrong.
对于那些声称""
和String.Empty
可以互换或者""
更好的人来说,你是非常错误的。
Each time you do something like myVariable = ""; you are creating an instance of an object. If Java's String object had an EMPTY public constant, there would only be 1 instance of the object ""
每次你做类似 myVariable = ""; 您正在创建一个对象的实例。如果 Java 的 String 对象有一个 EMPTY 公共常量,则对象“”将只有 1 个实例
E.g: -
例如:-
String.EMPTY = ""; //Simply demonstrating. I realize this is invalid syntax
myVar0 = String.EMPTY;
myVar1 = String.EMPTY;
myVar2 = String.EMPTY;
myVar3 = String.EMPTY;
myVar4 = String.EMPTY;
myVar5 = String.EMPTY;
myVar6 = String.EMPTY;
myVar7 = String.EMPTY;
myVar8 = String.EMPTY;
myVar9 = String.EMPTY;
10 (11 including String.EMPTY) Pointers to 1 object
10 个(包括 String.EMPTY 在内的 11 个)指向 1 个对象的指针
Or: -
或者: -
myVar0 = "";
myVar1 = "";
myVar2 = "";
myVar3 = "";
myVar4 = "";
myVar5 = "";
myVar6 = "";
myVar7 = "";
myVar8 = "";
myVar9 = "";
10 pointers to 10 objects
10 个指向 10 个对象的指针
This is inefficient and throughout a large application, can be significant.
这是低效的,并且在整个大型应用程序中可能很重要。
Perhaps the Java compiler or run-time is efficient enough to automatically point all instances of "" to the same instance, but it might not and takes additional processing to make that determination.
也许 Java 编译器或运行时的效率足以自动将 "" 的所有实例指向同一个实例,但它可能不会并且需要额外的处理来做出该决定。
回答by jade
Use org.apache.commons.lang.StringUtils.EMPTY
用 org.apache.commons.lang.StringUtils.EMPTY
回答by Slawomir
Don't just say "memory pool of strings is reused in the literal form, case closed". What compilers do under the hood is not the point here. The question is reasonable, specially given the number of up-votes it received.
不要只是说“字符串的内存池以文字形式重用,案例已关闭”。编译器在幕后所做的不是这里的重点。这个问题是合理的,特别是考虑到它收到的赞成票数量。
It's about the symmetry, without it APIs are harder to use for humans. Early Java SDKs notoriously ignored the rule and now it's kind of too late. Here are a few examples on top of my head, feel free to chip in your "favorite" example:
这是关于对称性的,没有对称性,API 更难为人类使用。众所周知,早期的 Java SDK 忽略了这条规则,现在为时已晚。以下是我头顶上的一些示例,请随意加入您“最喜欢”的示例:
- BigDecimal.ZERO, but no AbstractCollection.EMPTY, String.EMPTY
- Array.length but List.size()
- List.add(), Set.add() but Map.put(), ByteBuffer.put() and let's not forget StringBuilder.append(), Stack.push()
- BigDecimal.ZERO,但没有 AbstractCollection.EMPTY、String.EMPTY
- Array.length 但 List.size()
- List.add(), Set.add() 但 Map.put(), ByteBuffer.put() 还有我们不要忘记 StringBuilder.append(), Stack.push()