toarray

java: (String[])List.toArray() gives ClassCastException

三世轮回 提交于 2019-11-26 03:28:20
问题 The following code (run in android) always gives me a ClassCastException in the 3rd line: final String[] v1 = i18nCategory.translation.get(id); final ArrayList<String> v2 = new ArrayList<String>(Arrays.asList(v1)); String[] v3 = (String[])v2.toArray(); It happens also when v2 is Object[0] and also when there are Strings in it. Any Idea why? 回答1: This is because when you use toArray() it returns an Object[], which can't be cast to a String[] (even tho the contents are Strings) This is because