Efficiency of JList Search

此生再无相见时 提交于 2019-12-12 14:25:55

问题


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;
    }
}

回答1:


For a quick change, consider

String str = ((String)jList1.getModel().getElementAt(i));
str.substring(1, m_key.length()).equalsIgnoreCase(m_key);

And for one step beyond that, your own implementation of startsWithIgnoreCase which 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.




回答2:


Probably the quickest optimization (for time-to-code, not time-to-run), would be to sort the list and then do a binary search. You have a one-time up-front cost for the search (which, if this is used a lot, will get amortized away) and then you'll go from O(n) to O(log(n)). In my experience a binary search is relatively simple and uses the same data structures you already have.

Of course, a sorted n-tree structure will be faster algorithmically, but would require new data structures and more time in coding/testing. Decide where you want to spend your time.




回答3:


I disagree with all answer posted here (and little bit encrypted by JB Nizet). A possible alternative to JList is JTable with one Column (with or without TableHeader). JTable has a good implementation of Sorting and Filtering.




回答4:


Be sure to not browse all your list at each iteration. You could do (n!) iterations in the list where (n) is all you need.

If the list can be sort, used partial comparaison to reach the correct answers quickly. However if you have to create your own search function it could be messy.



来源:https://stackoverflow.com/questions/8918542/efficiency-of-jlist-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!