java empty string,为什么Java中没有String.Empty?

I understand that every time I type the string literal "", the same String object is referenced in the string pool.

But why doesn't the String API include a public static final String Empty = "";, so I could use references to 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 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.

Especially considering Strings 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.

Update

From your comment to the question:

What inspired this is actually

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值