简体   繁体   English

如何使用String.contains在Java中最佳搜索字符串列表?

[英]How to best search a list of string in java using String.contains?

Right now I'm working on an android application using voice recog. 现在,我正在使用语音识别在android应用程序上工作。 Basically, I'm wondering what the best search method is once I get String from voice recognition. 基本上,我想知道一旦从语音识别中得到String,最好的搜索方法是什么。 I'm currently using a linear search on the list of packagename, using the following to get that list: 我目前正在对包名列表使用线性搜索,并使用以下方法获取该列表:

    pkgNames = new ArrayList<String>();
    pkgAppsList = (ArrayList<ApplicationInfo>) getPackageManager()
            .getInstalledApplications(PackageManager.GET_META_DATA);

    // List available packages on phone.
    for (ApplicationInfo appInfo : pkgAppsList) {

        if (!isSystemPackage(appInfo))
            pkgNames.add(appInfo.packageName);
    }

I've decide that it's probably better to use the ApplicationInfo list(pkgAppsList) and do aa search on that, but is there a faster way of searching that list than just a simple linear search and using the result to open the Application with an Intent. 我已经决定使用ApplicationInfo列表(pkgAppsList)并对其进行搜索可能会更好,但是有没有比简单的线性搜索和使用结果以意图打开应用程序更快的搜索列表的方法? 。 Right now, all I can think of doing is: 现在,我能想到的就是:

    for(ApplicationInfo ai: pkgAppsList){
        if((ai.name).contains(voice_recog_result))
           //open Launch Intent for ai.packageName
    }

Is there a way faster search method I can use with the contains method or a way I can do this without the contains method? 有没有一种可以与contains方法一起使用的更快的搜索方法,或者一种不用contains方法可以做到这一点的方法?

For small numbers of searched strings (application names), the simplest method (traversing a linked list) should be chosen. 对于少量的搜索字符串(应用程序名称),应选择最简单的方法(遍历链表)。

Auto-growing hash tables are often used for similar tasks, but only if the set of searched strings is often large. 自动增长的哈希表通常用于类似的任务,但前提是搜索的字符串集通常很大。 The worst case performance of a hash table is the same as traversing a linked list (due to auto-growing, and due to the potential of mass hash value collisions), and it has non-negligible overhead. 哈希表的最坏情况性能与遍历链表相同(由于自动增长,并且由于存在大量哈希值冲突的可能性),并且开销不可忽略。 It is therefore not a great choice for "just in case" insurance against a longer set of strings. 因此,针对较长的字符串“以防万一”保险不是一个好选择。

The data structure that is theoretically fitted to this task is called trie . 理论上适合该任务的数据结构称为trie Tries are not part of JCL or Android libraries, but available implementations are available . 尝试不是JCL或Android库的一部分,但是可用的实现可用 The worst case performance of a trie is proportional to the length of the longest string, regardless of the number of strings. 特里琴在最坏情况下的性能与最长字符串的长度成正比,而与字符串的数量无关。 Tries however tend to take a lot of memory which makes them unsuitable for mobile environments. 但是,尝试会占用大量内存,这使其适合移动环境。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM