1

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

3 回答 3

6

CharSequence是类实现String的接口。所以可以持有任何这个实现类的 Object 并返回,试试 -StringBufferStringBuilderCharSequenceCharSequence#toStringString

String[] mEntriesString = new String[mEntries.length];
int i=0;
for(CharSequence ch: mEntries){
    mEntriesString[i++] = ch.toString(); 
}
于 2013-02-20T15:29:23.460 回答
1

CharSequence是一个接口。String类实现该接口。因此,您不能将其转换为String,就像您不能List转换为一样ArrayList,因为它不必是该具体类的实例

于 2013-02-20T15:29:39.577 回答
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;
}
于 2013-02-20T15:33:16.253 回答