为什么Java中没有String

为什么Java中没有String

本文介绍了为什么Java中没有String.Empty?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,每次输入字符串文字时,字符串池中都会引用相同的String对象。

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

但为什么String API不包含 public static final String Empty =; ,所以我可以使用对的引用String.Empty

But why doesn't the String API include a public static final String Empty = "";, so I could use references to String.Empty?

它至少可以节省编译时间,因为编译器会知道引用现有的String,并且不必检查它是否已经被创建用于重用,对吧?我个人认为,在许多情况下,字符串文字的扩散,特别是微小字符串,是一种代码味道。

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 是12个字符,而是两个,它们在运行时都会在内存中引用完全相同的实例。我不完全确定为什么 String.EMPTY 会在编译时节省,实际上我认为它会是后者。

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 s是不可变的,它不像你可以先得到一个空字符串,并对它执行一些操作 - 最好使用 StringBuilder (或 StringBuffer 如果你想要是线程安全的)并把它变成一个字符串。

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:

我认为在适当的类中提供常量是完全合法的:

I believe it would be totally legitimate to provide a constant in your appropriate class:

private static final String EMPTY_STRING = "";

然后在代码中引用它

TextBox.setText(EMPTY_STRING);

这样至少你明确表示你想要一个空字符串,而不是你忘记填写在IDE中的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.

这篇关于为什么Java中没有String.Empty?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:22