我一直认为CharSequence []和String []是必不可少的,但是:
我有一些代码包含以下内容:
CharSequence[] mEntries;
...
String[] mEntriesString = (String[]) mEntries;
ListAdapter adapter = new ArrayAdapter<String>(getContext(), R.layout.two_lines_list_preference_row, mEntriesString)
当代码运行时,我得到了
java.lang.ClassCastException: java.lang.CharSequence[] cannot be cast to java.lang.String[]
那么两个问题?
答案 0 :(得分:6)
CharSequence
是String
,StringBuffer
,StringBuilder
类实现的接口。因此,CharSequence
可以保存此实现类的任何对象并CharSequence#toString
返回String
,尝试 -
String[] mEntriesString = new String[mEntries.length];
int i=0;
for(CharSequence ch: mEntries){
mEntriesString[i++] = ch.toString();
}
答案 1 :(得分:1)
CharSequence
是一个界面。 String
类实现该接口。因此,您无法将其强制转换为String
,就像您无法将List
强制转换为ArrayList
一样,因为它不必是该具体类的实例
答案 2 :(得分:1)
您无法将引用CharSequence[]
投射到String[]
。
你只能在那种情况下施放它:
CharSequence[] charSequencesAsString = new String[] { "test" };
String[] result = (String[]) charSequencesAsString;
System.out.println(Arrays.toString(result));
解决问题的安全方法:
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;
}