【问题标题】:[Ljava.lang.Object; cannot be cast to [Ljava.lang.String; [duplicate][Ljava.lang.Object; cannot be cast to [Ljava.lang.String; [duplicate]
【发布时间】:2018-05-04 16:28:01
【问题描述】:

以下代码(在 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;

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

【问题讨论】:

  • 与问题无关,但您可能不应该从 EDT 运行这段代码。

标签: java list netbeans classcastexception toarray


【解决方案1】:

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

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

这样:

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

【讨论】:

  • idk 为什么不赞成,回复似乎是正确的,我只想补充一点,您应该使用空数组作为初始化参数:list.toArray(new String[0]); 查看更多:stackoverflow.com/a/53285440/4270929
猜你喜欢
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多