javalistnetbeansclasscastexceptiontoarray

[Ljava.lang.Object; cannot be cast to [Ljava.lang.String;


The following code (run in netbeans) always gives me a ClassCastException in the last line:

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());
}

when I run the code, I get the following Error:

    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

I tried also to not cast it but it gives me an error. Could someone please help me? I'm really confused with this!


Solution

  • Use the overloaded List.toArray() method that specifies the return type of the array :

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

    In this way :

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