0

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!

xingbin
  • 27,410
  • 9
  • 53
  • 103
  • 1
    Not related to the problem, but you probably shouldn't be running this piece of code from the EDT. – Renatols May 04 '18 at 16:35

1 Answers1

0

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()]);     
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • idk why downvoted, reply seems correct, I would only add that you should use empty array as argument for initialization: `list.toArray(new String[0]);` see more: https://stackoverflow.com/a/53285440/4270929 – Paweł Sosnowski Nov 18 '20 at 13:46