Search code examples
javajlistsubsettreesetsortedset

What's a more efficient alternative than converting a SortedSet to a Vector in Java?


I'm writing a contact book application in Java. The Contacts are displayed on a JList which uses a Sorted TreeSet list model.

I've added a search field and I've added a key listener to it. With each key entered, the subset function of the list model is used to display a narrowed down set of contacts. I want the JList to display this narrowed down subset.

I'm thinking of converting the SortedSet to a Vector and then using the JList's setListData method to display the results but I know this would be slow and inefficient, and is an even worse idea when you're using a key listener.

So I would like to ask, what's the most efficient way to solve this problem.

Thanks for your help.


Solution

  • I would extend AbstractListModel and use the Set/subSet directly as the source of the data displayed by the JList. Each time you replace the current subset by another one in the model, call fireContentsChanged to make the view (the JList) aware of the change.

    This way, there's no need to convert the Set to a Vector.