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!

1
  • 1
    Not related to the problem, but you probably shouldn't be running this piece of code from the EDT. Commented May 4, 2018 at 16:35

1 Answer 1

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()]);     
Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/a/53285440/4270929

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.