java - [Ljava.lang.Object; 不能转换为 [Ljava.lang.String;
问题描述
以下代码(在 netbeans 中运行)总是在最后一行给我一个 ClassCastException:
private void GetModules() throws SQLException {
stm = conn.prepareStatement("SELECT * FROM module");
Rs = stm.executeQuery();
Lliste.clear();
modules.clear();
while (Rs.next()) {
String[] str_l = new String[5];
for (int i = 0; i < 5; i++)
str_l[i] = Rs.getString(i + 1);
Lliste.add(str_l);
modules.add(str_l[1]);
}
stm.close();
Rs.close();
liste.setListData((String[]) modules.toArray());
}
当我运行代码时,出现以下错误:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
我也尝试不投射它,但它给了我一个错误。有人可以帮我吗?我真的很困惑这个!
解决方案
使用指定数组返回类型的重载List.toArray()方法:
public <T> T[] toArray(T[] a)
这样 :
liste.setListData(modules.toArray(new String[modules.size()]);
推荐阅读
- google-analytics - Google Analytics(分析)自定义维度未跟踪
- google-chrome - 如何同时显示样式和计算?
- java - 将图像转换为固定格式以丢弃所有额外的注释
- react-native - React-native 短信检索器未按预期工作
- json - 您现在知道如何更新函数中的 json 吗?(API,角度)
- c++ - ctest 报告退出状态为 1 的测试成功
- javascript - Firebase 函数无法获取从 Angular9 中的简单联系表单发送的请求值
- r - 在 R 中,如何一次性在数据帧上使用 p.adjust 的所有方法?
- java - 来自存储库的 .save() 方法循环调用的 StackOverflowError
- kubernetes - JIRA LDAP 目录同步失败的 Microsoft Azure Active Directory 单点登录