首页 > 解决方案 > [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;

我也尝试不投射它,但它给了我一个错误。有人可以帮我吗?我真的很困惑这个!

标签: javalistnetbeansclasscastexceptiontoarray

解决方案


使用指定数组返回类型的重载List.toArray()方法:

public <T> T[] toArray(T[] a)

这样 :

liste.setListData(modules.toArray(new String[modules.size()]);     

推荐阅读