CharSequence VS String in Java?

Programming in Android, most of the text values are expected in CharSequence .

Why is that? What is the benefit, and what are the main impacts of using CharSequence over String?

What are the main differences, and what issues are expected, while using them, and converting from one to another?


Strings are CharSequences, so you can just use Strings and not worry. Android is merely trying to be helpful by allowing you to also specify other CharSequence objects, like StringBuffers.


I believe it is best to use CharSequence. The reason is that String implements CharSequence, therefore you can pass a String into a CharSequence, HOWEVER you cannot pass a CharSequence into a String, as CharSequence doesn't not implement String. ALSO, in Android the EditText.getText() method returns an Editable, which also implements CharSequence and can be passed easily into one, while not easily into a String. CharSequence handles all!


This class diagram may help you see the big picture of string types in Java 7/8. I'm not sure if all of these are present in Android, but the overall context may still prove useful to you.

Also, note the comments made on the accepted Answer. The CharSequence interface was retrofitted onto existing class structures, so there are some important subtleties ( equals() & hashCode() ). Notice the various versions of Java (1, 2, 4 & 5) tagged on the classes/interfaces—quite a bit of churn over the years. Ideally CharSequence would have been in place from the beginning, but such is life.

各种与字符串相关的类和接口的图表

链接地址: http://www.djcxy.com/p/72206.html

上一篇: t c中的格式说明符?

下一篇: 在Java中CharSequence VS字符串?