Search code examples
javaswinglistarraylistjlist

Putting an ArrayList into a JList using ArrayList#toArray method


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)*/

Solution

  • 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);