Reputation: 4881
I always thought CharSequence[] and String[] were essential the same, however :
I have some code that has the following :
CharSequence[] mEntries;
...
String[] mEntriesString = (String[]) mEntries;
ListAdapter adapter = new ArrayAdapter<String>(getContext(), R.layout.two_lines_list_preference_row, mEntriesString)
When the code runs I get
java.lang.ClassCastException: java.lang.CharSequence[] cannot be cast to java.lang.String[]
So two questions ?
Upvotes: 1
Views: 9097
Reputation: 38625
You can not cast reference CharSequence[]
into String[]
.
You can cast it only in that situation:
CharSequence[] charSequencesAsString = new String[] { "test" };
String[] result = (String[]) charSequencesAsString;
System.out.println(Arrays.toString(result));
Safe way to solve your problem:
public static void main(String[] args) {
CharSequence[] charSequencesAsString = new String[] { "test" };
CharSequence[] charSequencesAsCharSequence = new CharSequence[] { "test" };
CharSequence[] charSequencesAsStringBuilder = new StringBuilder[] { new StringBuilder("Test") };
String[] stringsFromStrings = convertToStringArray(charSequencesAsString);
String[] stringsFromCharSequence = convertToStringArray(charSequencesAsCharSequence);
String[] stringsFromStringBuilder = convertToStringArray(charSequencesAsStringBuilder);
System.out.println("Same array after conversion: " + (stringsFromStrings == charSequencesAsString));
System.out.println("Same array after conversion: " + (stringsFromCharSequence == charSequencesAsCharSequence));
System.out.println("Same array after conversion: " + (stringsFromStringBuilder == charSequencesAsStringBuilder));
}
public static String[] convertToStringArray(CharSequence[] charSequences) {
if (charSequences instanceof String[]) {
return (String[]) charSequences;
}
String[] strings = new String[charSequences.length];
for (int index = 0; index < charSequences.length; index++) {
strings[index] = charSequences[index].toString();
}
return strings;
}
Upvotes: 1
Reputation: 41200
CharSequence
is interface which String
, StringBuffer
, StringBuilder
classes implements. So CharSequence
can hold any of this implementation class's Object And CharSequence#toString
returns String
, try -
String[] mEntriesString = new String[mEntries.length];
int i=0;
for(CharSequence ch: mEntries){
mEntriesString[i++] = ch.toString();
}
Upvotes: 6
Reputation: 4620
CharSequence
is an Interface. String
class implements that interface. So, you cannot cast it to String
, the same way you cannot cast List
to ArrayList
, because it doesn't have to be an instance of that concrete class
Upvotes: 1