0

I'm having trouble using the toArray method of the ArrayList class. I need to put the content of an ArrayList, vecPersonnages, into a JList, listeObjets, and I'd like to do it using ArrayList#toArray method. I managed to make it work by putting the values of my list in a tab and then putting this tab in the JList.

I did check on Google for help but everything that i found turned out not to work. I do have a toString method in my classes, however, i do not have a toString method in the class in which I utilize my JList.

This is how i declared my classes:

private JList<Personnage> listeObjets = null;
private ArrayList<Personnage> vecPersonnages = null;

Below is the code where I try to add the content of my ArrayList to the JList along with some things I tried, noted in comments:

Personnage[] tabPerso = new Personnage[vecPersonnages.size()];
for (int i = 0; i < vecPersonnages.size(); i++) {
    tabPerso[i] = vecPersonnages.get(i);
}
listeObjets.setListData(tabPerso);
//listeObjets.setListData(vecPersonnages.toArray());
//listeObjets.setListData((Personnage[]) vecPersonnages.toArray());
/*the last line gives me a ClassCastException (java.lang.Object 
  cannot be cast to personnage.Personnage)*/

1 Answer 1

3

Use the overloaded method of toArray(), toArray(T[] a);

Personnage[] array = new Personnage[vecPersonnages.size()]; //Create a new array with the size of the ArrayList
vecPersonnages.toArray(array); // fill the array
listeObjets.setListData(array);
Sign up to request clarification or add additional context in comments.

1 Comment

@user2249860 You are welcome. If this answers your question, check the right mark to make this answer as the right one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.