Search code examples
javalistswingjlistdefaultlistmodel

Convert DefaultListModel to List in Java


I'm making a Swing application that includes a JList and all the objects in the list are stored in a DefaultListModel. At the same time I need to pass the list to a method that receives as input a List. How can i convert a DefaultListModel to a List ?

This is the error i got:

The method computeSpending(List<Subscription>) in the type SubscriptionSpending is not applicable for the arguments (DefaultListModel<Subscription>)

Solution

  • How can i convert a DefaultListModel to a List ?

    Arrays.asList(defaultListModel.toArray());


    Description:

    DefaultListModel is not a subclass of List. So it is not directly possible to pass that as a List argument. Instead you can change the parameter type to ListModel<E>. Such as:

    computeSpending(ListModel<Subscription>)
    

    Also, If you must need to pass the DefaultListModel<Subscription> into a List, you can use:

    List<Subscription> asList = Arrays.asList(defaultListModel.toArray());