将Object数组转换为String数组会引发ClassCastException [英] Casting Object array into String array throws ClassCastException

查看:79
本文介绍了将Object数组转换为String数组会引发ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<String> list = getNames();//this returns a list of names(String).

String[] names = (String[]) list.toArray(); // throws class cast exception.

我不明白为什么?任何解决方案,请多多解释.

I don't understand why ? Any solution, explanation is appreciated.

推荐答案

这是因为无参数的 toArray 会生成 Object 的数组.您需要调用将输出数组作为参数的重载,并传递一个 String s数组,如下所示:

This is because the parameterless toArray produces an array of Objects. You need to call the overload which takes the output array as the parameter, and pass an array of Strings, like this:

String[] names = (String[]) list.toArray(new String[list.size()]);

在Java 5或更高版本中,您可以删除演员表.

In Java 5 or newer you can drop the cast.

String[] names = list.toArray(new String[list.size()]);

这篇关于将Object数组转换为String数组会引发ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆