how to convert string to Charsequence in JAVA...????
+15
A:
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.
Hope it helps.
JG
2009-09-08 04:34:17
Except that you can't assign a `CharSequence` to a `String` without an explicit cast.
gustafc
2009-09-08 06:26:28
Fixed the example, thanks. I meant the other way around, i.e., assign a `String` to a `CharSequence`.
JG
2009-09-09 00:24:29
I'm confused by this code "CharSequence cs = "string"; ". How can we instantiate a CharSequence? Isn't that an Interface? (Sorry I'm still learning Java).
Mugen
2010-10-16 10:41:08
You are correct. It is indeed an interface. However, that code does not instantiate a `CharSequence`. It simply assigns an instance of `String` to a `CharSequence` variable, and since `String` implements the `CharSequence` interface, the code works.
JG
2010-10-16 12:06:19