tags:

views:

169

answers:

3

Is it possible to make a DefaultListModel use the contents of a LinkedList to display?

This is then to be used with a JList.

+3  A: 

Yes it is possible: You simply need to subclass AbstractListModel and override getElementAt and getSize to call through to your underlying LinkedList.

public class MyListModel extends AbstractListModel {
  private final List<?> l;

  public MyListModel(List<?> l) {
    this.l = l;
  }

  public Object getElementAt(int index) {
    return l.get(index);
  }

  public int getSize() {
    return l.size();
  }
}

Warning: When implementing ListModel or TableModel and backing the model with a List I would advise using ArrayList over LinkedList to ensure O(1) access time when accessing a given element.

Adamski
A: 

Unless you subclass it and override all of the implemented methods, no. but you can add all of the elements from a LinkedList to the DefaultListModel (populating the underlying Vector)

for (Object element : linkedList)
    model.addElement(element);

or just write your own implementation of AbstractListModel using a LinkedList/List/Collection as the source.

pstanton
+1  A: 

DefaultListModel uses a Vector as the backing list. This is a private member, so you don't really have an option extend and override how it works. If you have to use a LinkedList, you'll probably have to write your own list model implementation (say, extend AbstractListModel as the default list model does), or loop through your list and add each object to the list model.

Ash