How to convert a String to CharSequence?
Solution 1:
Since String
IS-A CharSequence
, you can pass a String
wherever you need a CharSequence
, or assign a String
to a CharSequence
:
CharSequence cs = "string";
String s = cs.toString();
foo(s); // prints "string"
public void foo(CharSequence cs) {
System.out.println(cs);
}
If you want to convert a CharSequence
to a String
, just use the toString
method that must be implemented by every concrete implementation of CharSequence
.
Solution 2:
Straight answer:
String s = "Hello World!";
// String => CharSequence conversion:
CharSequence cs = s; // String is already a CharSequence
CharSequence
is an interface, and the String
class implements CharSequence
.
Solution 3:
CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.
So, just as you use InterfaceName i = new ItsImplementation()
, you can use CharSequence cs = new String("string")
or simply CharSequence cs = "string";
Solution 4:
You can use
CharSequence[] cs = String[] {"String to CharSequence"};