I have to put all elements from a DefaultListModel (in a listbox) into a List<Object>. How can I do that in Java?
views:
122answers:
3Depends if you want to copy the data or leave it connected.
Tom Hawtin - tackline
2009-10-29 16:09:35
+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
2009-10-29 16:19:11