I came across some java code for doing a prefix search on a JList. Looking at it however, the meat of the algorithm is quite inefficient, using a linear search over the list for each keypress, and doing a slow case conversion within the tight loop.
I would imagine for very large amounts of data, a custom-implemented ternary search tree would be a much more efficient solution. However, if one was striving for simple code and did not have the performance requirements necessitating such complexities, are there other more simplistic ways this algorithm could be improved without necessitating significant amounts of additional code?
for (int i=0; i < jList1.getModel().getSize(); i++) {
String str = ((String)jList1.getModel().getElementAt(i)).toLowerCase();
if (str.startsWith(m_key)) {
jList1.setSelectedIndex(i);
jList1.ensureIndexIsVisible(i);
break;
}
}
For a quick change, consider
And for one step beyond that, your own implementation of
startsWithIgnoreCasewhich should be quick and easy to write.EDIT: This seems to be scrolling a list to the element that matches user input. You should definitely consider a more sophisticated data structure. This is done a lot, you might be able to find some efficient algorithm on the net.