【问题标题】:Java Collection and MapJava 集合和映射
【发布时间】:2014-01-10 02:41:14
【问题描述】:

我正在使用 Edittext 和 Listview 制作一个 android 应用程序。在那我想使用java集合来存储项目,然后在该列表集合中搜索项目。 我的搜索方法是: 首先,我们将项目添加到集合中。 然后,当我们在 Edittext 中键入单词的启动字母时,该列表将获取以该字母开头的单词的索引,并将 setSelection 设置为该索引的列表视图。 示例:我输入a,然​​后它会选择苹果,然后.....等等。

我想知道什么样的收藏和地图可以帮助我解决这个问题? 提前致谢。

【问题讨论】:

    标签: java android list collections


    【解决方案1】:

    如果您只查看输入的第一个字符,而不是单词的后续字符,那么一个简单的解决方案可能是您希望的字母表的数组处理,并让它持有 StringArrayList。这非常简单,重量轻,性能也很好,见下文:

        // Create an array with the alphabet from 'a' to 'z' (i.e. English alphabet)
        List<String>[] firstCharLookup = new List[26];
    
        // Initialize the array to avoid NullPointerException's
        for (int i = 0; i < firstCharLookup.length; i++) {
            firstCharLookup[i] = new ArrayList<String>();
        }
    
        // Fill your collections with the strings in the appropriate collections.
        firstCharLookup[0].add("apple");
        firstCharLookup[0].add("active");
        firstCharLookup[0].add("addict");
    
        firstCharLookup[1].add("bee");
        firstCharLookup[1].add("busy");
        firstCharLookup[1].add("bus");
        // ...
        // Continue with filling dictionary
    
    
        // If user types 'a' or 'A' then lowercase the character, then:
        char firstLookup = 'a';
        System.out.println(firstCharLookup[firstLookup - 'a']);
        // We subtract by 'a' so that we get a '0' based index
    
        // If user types 'b', then:
        char secondLookup = 'b';
        System.out.println(firstCharLookup[secondLookup - 'a']);
    

    【讨论】:

      【解决方案2】:

      也许你应该看看那个

      源代码:http://chathura-lakmal.blogspot.fr/2010/10/how-to-choose-correct-java-collection.html

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        我会使用特里树 https://community.oracle.com/thread/2070706。这里的例子很好地解释了它。可以指定前缀,遍历树得到所有单词

        【讨论】:

          猜你喜欢
          • 2018-03-30
          • 2013-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-22
          相关资源
          最近更新 更多