tags:

views:

122

answers:

3

I have to put all elements from a DefaultListModel (in a listbox) into a List<Object>. How can I do that in Java?

+5  A: 
Arrays.asList(model.toArray());
jarnbjo
Depends if you want to copy the data or leave it connected.
Tom Hawtin - tackline
+1  A: 

According to ye olde API, you'll need to use the elements() method and iterate over them, adding them to a list. DefaultListModel is not in the same hierarchy as the normal Collections classes.

OR use what jarnbjo suggested!

Malaxeur
+3  A: 

If you want to make a copy of the contents, then you can use DefaultListModel.toArray to get the data and construct your favourite List implementation with that. Alternatively you can loop over ListModel.getElementAt ListModel.getSize times.

If you want a live connection between the collections rather than a copy, use AbstractList:

 public static List<Object> asList(final DefaultListModel model) {
     return new AbstractList<Object>() {
          @Override public Object get(int index) {
              return        model.getElementAt(index);
          }
          ...
     };
 }

You may want to slide Class.cast in there, but there is an inherent problem with Swing types not being generic.

Tom Hawtin - tackline