In Android a CharSequence is an umbrella for various types of text strings. Here are some of the common ones: String (immutable text with no styling spans)
CharSequence is a contract (interface), and String is an implementation of this contract. The documentation for CharSequence is: A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences.
1.0. interface CharSequence. Represents a readable sequence of Char values.
By invoking its toString()
method.
Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.
There is a subtle issue here that is a bit of a gotcha.
The toString()
method has a base implementation in Object
. CharSequence
is an interface; and although the toString()
method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence
toString()
method's javadoc puts on the toString()
method; ie that it should return a string containing the characters in the order returned by charAt()
.
Your IDE won't even help you out by reminding that you that you probably should override toString()
. For example, in intellij, this is what you'll see if you create a new CharSequence
implementation: http://puu.sh/2w1RJ. Note the absence of toString()
.
If you rely on toString()
on an arbitrary CharSequence
, it should work provided the CharSequence
implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder
and append()
, like so:
final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
You can directly use String.valueOf()
String.valueOf(charSequence)
Though this is same as toString()
it does a null check on the charSequence
before actually calling toString.
This is useful when a method can return either a charSequence
or null
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With