转换CharSequence []和CharSequence []

时间:2013-02-20 15:26:17

标签: java android

我一直认为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[]

那么两个问题?

  • 为什么这种情况不会发生
  • 为什么ArrayAdapter不允许在其构造函数中使用CharSequence []。

3 个答案:

答案 0 :(得分:6)

CharSequenceStringStringBufferStringBuilder类实现的接口。因此,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;
}