Java集合和地图

时间:2013-12-21 08:32:26

标签: java android list collections

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

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

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

    // 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']);